欢迎来到山村网

Python通过select实现异步IO的方法

2019-03-02 13:50:45浏览:940 来源:山村网   
核心摘要:  本文实例讲述了Python通过select实现异步IO的方法。分享给大家供大家参考。具体如下:  在Python中使用select与poll

  本文实例讲述了Python通过select实现异步IO的方法。分享给大家供大家参考。具体如下:

  在Python中使用select与poll比起在C中使用简单得多。select函数的参数是3个列表,包含整数文件描述符,或者带有可返回文件描述符的fileno()方法对象。第一个参数是需要等待输入的对象,第二个指定等待输出的对象,第三个参数指定异常情况的对象。第四个参数则为设置超时时间,是一个浮点数。指定以秒为单位的超时值。select函数将会返回一组文件描述符,包括输入,输出以及异常。

  在linux下利用select实现多路IO的文件复制程序:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #!/usr/bin/env python import select #导入select模块 BLKSIZE=8192 def readwrite(fromfd,tofd): readbuf = fromfd.read(BLKSIZE) if readbuf: tofd.write(readbuf) tofd.flush() return len(readbuf) def copy2file(fromfd1,tofd1,fromfd2,tofd2): ''' using select to choice fds''' totalbytes=0 if not (fromfd1 or fromfd2 or tofd1 or tofd2) : #检查所有文件描述符是否合法 return 0 while True: #开始利用select对输入所有输入的文件描述符进行监视 rs,ws,es = select.select([fromfd1,fromfd2],[],[]) for r in rs: if r is fromfd1: #当第一个文件描述符可读时,读入数据 bytesread = readwrite(fromfd1,tofd1) totalbytes += bytesread if r is fromfd2: bytesread = readwrite(fromfd2,tofd2) totalbytes += bytesread if (bytesread <= 0): break return totalbytes def main(): fromfd1 = open("/etc/fstab","r") fromfd2 = open("/etc/passwd","r") tofd1 = open("/root/fstab","w+") tofd2 = open("/root/passwd","w+") totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2) print "Number of bytes copied %dn" % totalbytes return 0 if __name__=="__main__": main()

  希望本文所述对大家的Python程序设计有所帮助。

(责任编辑:豆豆)
下一篇:

Python通过poll实现异步IO的方法

上一篇:

C#实现窗口之间的传值

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com