欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python通過poll實(shí)現(xiàn)異步IO的方法

 更新時(shí)間:2015年06月04日 10:26:58   作者:raygtr  
這篇文章主要介紹了Python通過poll實(shí)現(xiàn)異步IO的方法,實(shí)例分析了poll方法實(shí)現(xiàn)異步IO的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了Python通過poll實(shí)現(xiàn)異步IO的方法。分享給大家供大家參考。具體分析如下:

在使用poll()后返回輪詢對(duì)象,該對(duì)象支持以下方法:
pollObj.register(fd,[,eventmask])第一個(gè)參數(shù)是注冊(cè)新的文件描述符fd,fd要么是一個(gè)整數(shù)文件描述符,要么可以帶有一個(gè)獲取文件描述符的fileno()方法的對(duì)象。eventmask是一些按位或標(biāo)記,這些標(biāo)記指示要處理的事件。

POLLIN:       用于讀取數(shù)據(jù)
POLLPRI:      用于讀取緊急數(shù)據(jù)
POLLOUT:      準(zhǔn)備寫入
POLLERR:      錯(cuò)誤情況
POLLHUP:      保持狀態(tài)
POLLNVAL:     無效請(qǐng)求

最后在循環(huán)中利用pollObj.poll()來進(jìn)行對(duì)已注冊(cè)的文件描述符進(jìn)行輪詢。返回一元祖(fd,event)。其中fd是文件描述符,event是指示時(shí)間的位掩碼。至需要將event與對(duì)應(yīng)的時(shí)間進(jìn)行&測(cè)試即可。

利用poll創(chuàng)建對(duì)一個(gè)多路文件復(fù)制程序,代碼如下:

#!/usr/bin/env python
import select
BLKSIZE=8192
def readwrite(fromfd,tofd):
  readbuf = fromfd.read(BLKSIZE)
  if readbuf:
    tofd.write(readbuf)
    tofd.flush()
  return len(readbuf)
def copyPoll(fromfd1,tofd1,fromfd2,tofd2):
  #定義需要監(jiān)聽的事件
  READ_ONLY = (select.POLLIN |
       select.POLLPRI |
      select.POLLHUP |
      select.POLLERR )
  totalbytes=0
    if not (fromfd1 or fromfd2 or tofd1 or tofd2) :
    return 0
  fd_dict = {fromfd1.fileno():fromfd1,fromfd2.fileno():fromfd2}
  #創(chuàng)建poll對(duì)象p
  p=select.poll()
  #利用poll對(duì)象p對(duì)需要監(jiān)視的文件描述符進(jìn)行注冊(cè)
  p.register(fromfd1,READ_ONLY)
  p.register(fromfd2,READ_ONLY)
  while True:
  #輪詢已經(jīng)注冊(cè)的文件描述符是否已經(jīng)準(zhǔn)備好
    result = p.poll()
    if len(result) != 0:
      for fd,events in result:
        if fd_dict[fd] is fromfd1:
          if events & (select.POLLIN|select.POLLPRI):
            bytesread = readwrite(fromfd1,tofd1)
            totalbytes+=bytesread
          elif events & (select.POLLERR):
            p.unregister(fd_dict[fd])
        if fd_dict[fd] is fromfd2:
          if events & (select.POLLIN|select.POLLPRI):
            bytesread = readwrite(fromfd2,tofd2)
            totalbytes+=bytesread
          elif events & (select.POLLERR):
            p.unregister(fd_dict[fd])
    if bytesread <= 0:  
      break
  return totalbytes
def main():
  fromfd1 = open("/etc/fstab","r")
  fromfd2 = open("/root/VMwareTools-8.8.1-528969.tar.gz","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()

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論