歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python select實現異步IO

Python select實現異步IO

日期:2017/3/1 10:14:02   编辑:Linux編程

在Python中使用select與poll比起在C中使用簡單得多。select函數的參數是3個列表,包含整數文件描述符,或者帶有可返回文件描述符的fileno()方法對象。第一個參數是需要等待輸入的對象,第二個指定等待輸出的對象,第三個參數指定異常情況的對象。第四個參數則為設置超時時間,是一個浮點數。指定以秒為單位的超時值。select函數將會返回一組文件描述符,包括輸入,輸出以及異常。

在linux下利用select實現多路IO的文件復制程序:

  1. #!/usr/bin/env python


  2. import select
  3. #導入select模塊

  4. BLKSIZE=8192

  5. def readwrite(fromfd,tofd):
  6. readbuf = fromfd.read(BLKSIZE)
  7. if readbuf:
  8. tofd.write(readbuf)
  9. tofd.flush()
  10. return len(readbuf)

  11. def copy2file(fromfd1,tofd1,fromfd2,tofd2):
  12. ''' using select to choice fds'''
  13. totalbytes=0
  14. if not (fromfd1 or fromfd2 or tofd1 or tofd2) :
  15. #檢查所有文件描述符是否合法
  16. return 0
  17. while True:
  18. #開始利用select對輸入所有輸入的文件描述符進行監視
  19. rs,ws,es = select.select([fromfd1,fromfd2],[],[])
  20. for r in rs:

  21. if r is fromfd1:
  22. #當第一個文件描述符可讀時,讀入數據
  23. bytesread = readwrite(fromfd1,tofd1)
  24. totalbytes += bytesread
  25. if r is fromfd2:
  26. bytesread = readwrite(fromfd2,tofd2)
  27. totalbytes += bytesread
  28. if (bytesread <= 0):
  29. break
  30. return totalbytes
  31. def main():

  32. fromfd1 = open("/etc/fstab","r")
  33. fromfd2 = open("/etc/passwd","r")

  34. tofd1 = open("/root/fstab","w+")
  35. tofd2 = open("/root/passwd","w+")

  36. totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2)

  37. print "Number of bytes copied %d\n" % totalbytes
  38. return 0



  39. if __name__=="__main__":
  40. main()
Copyright © Linux教程網 All Rights Reserved