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

php中文网
发布: 2016-06-06 11:18:07
原创
1518人浏览过

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

在使用poll()后返回轮询对象,该对象支持以下方法:
pollObj.register(fd,[,eventmask])第一个参数是注册新的文件描述符fd,fd要么是一个整数文件描述符,要么可以带有一个获取文件描述符的fileno()方法的对象。eventmask是一些按位或标记,这些标记指示要处理的事件。

POLLIN:       用于读取数据
POLLPRI:      用于读取紧急数据
POLLOUT:      准备写入
POLLERR:      错误情况
POLLHUP:      保持状态
POLLNVAL:     无效请求

最后在循环中利用pollObj.poll()来进行对已注册的文件描述符进行轮询。返回一元祖(fd,event)。其中fd是文件描述符,event是指示时间的位掩码。至需要将event与对应的时间进行&测试即可。

利用poll创建对一个多路文件复制程序,代码如下:

FlowIn
FlowIn

AI 时代下的内容共创平台,借助 FlowIn AI 撰写与改写内容十分便利。

FlowIn 324
查看详情 FlowIn

#!/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):
  #定义需要监听的事件
  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}
  #创建poll对象p
  p=select.poll()
  #利用poll对象p对需要监视的文件描述符进行注册
  p.register(fromfd1,READ_ONLY)
  p.register(fromfd2,READ_ONLY)
  while True:
  #轮询已经注册的文件描述符是否已经准备好
    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()
登录后复制

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

相关标签:
python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号