SoFunction
Updated on 2024-11-18

Python's implementation of asynchronous IO via polls

This article example describes how Python implements asynchronous IO via poll. Shared for your reference. Specific analysis is as follows:

Returns the polling object after using poll(), which supports the following methods:
(fd,[,eventmask]) The first argument is to register a new file descriptor, fd. fd is either an integer file descriptor or can be an object with a fileno() method that gets the file descriptor. eventmask is some per-position or marker that indicates the event to be processed.

POLLIN: for reading data
POLLPRI: for reading emergency data
POLLOUT: Prepare to write
POLLERR: Error condition
POLLHUP: Hold state
POLLNVAL: invalid request

Finally, polling for registered file descriptors is performed in a loop using (). Returns a one-dimensional ancestor (fd,event). Where fd is the file descriptor and event is a bitmask indicating the time. To the need to event and the corresponding time for & test can be.

Use poll to create a pair of multiplexed file copy programs with the following code:

#!/usr/bin/env python
import select
BLKSIZE=8192
def readwrite(fromfd,tofd):
  readbuf = (BLKSIZE)
  if readbuf:
    (readbuf)
    ()
  return len(readbuf)
def copyPoll(fromfd1,tofd1,fromfd2,tofd2):
  # Define events to listen for
  READ_ONLY = ( |
        |
       |
       )
  totalbytes=0
    if not (fromfd1 or fromfd2 or tofd1 or tofd2) :
    return 0
  fd_dict = {():fromfd1,():fromfd2}
  # Create poll object p
  p=()
  # Register the file descriptors to be monitored using the poll object p
  (fromfd1,READ_ONLY)
  (fromfd2,READ_ONLY)
  while True:
  # Polling registered file descriptors for readiness
    result = ()
    if len(result) != 0:
      for fd,events in result:
        if fd_dict[fd] is fromfd1:
          if events & (|):
            bytesread = readwrite(fromfd1,tofd1)
            totalbytes+=bytesread
          elif events & ():
            (fd_dict[fd])
        if fd_dict[fd] is fromfd2:
          if events & (|):
            bytesread = readwrite(fromfd2,tofd2)
            totalbytes+=bytesread
          elif events & ():
            (fd_dict[fd])
    if bytesread <= 0:  
      break
  return totalbytes
def main():
  fromfd1 = open("/etc/fstab","r")
  fromfd2 = open("/root/VMwareTools-8.8.","r")
  tofd1 = open("/root/fstab","w+")
  tofd2 = open("/var/passwd","w+")
  totalbytes = copyPoll(fromfd1,tofd1,fromfd2,tofd2)
  print "Number of bytes copied %d\n" % totalbytes
  return 0
if __name__=="__main__":
  main()

I hope that what I have described in this article will help you in your Python programming.