• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 23次浏览 已收录 0个评论

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

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

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

#!/usr/bin/env pythonimport select#导入select模块BLKSIZE=8192def 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 totalbytesdef main():  fromfd1 = open("/etc/fstab","r")  fromfd2 = open("/etc/passwd","r")  tofd1 = open(<strong>本文来源gao@daima#com搞(%代@#码@网2</strong>"/root/fstab","w+")  tofd2 = open("/root/passwd","w+")  totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2)  print "Number of bytes copied %d\n" % totalbytes  return 0if __name__=="__main__":  main()

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python通过select实现异步IO的方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址