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

yipeiwu_com5年前Python基础

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

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

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

#!/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 %d\n" % totalbytes
  return 0
if __name__=="__main__":
  main()

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

相关文章

python安装virtualenv虚拟环境步骤图文详解

python安装virtualenv虚拟环境步骤图文详解

一、安装virtualenv 点击左下角最边上菜单栏输入cmd,打开命令行 2.根据版本的不同输入命令pip install virtualenv(或者pip3 install vir...

在Python中实现替换字符串中的子串的示例

假如有个任务: 给定一个字符串,通过查询字典,来替换给定字符中的变量。如果使用通常的方法: >>> "This is a %(var)s" % {"var":"do...

Python文件的读写和异常代码示例

一、从文件中读取数据 #!/usr/bin/env python with open('pi') as file_object: contents = file_object.r...

Python实现的读取电脑硬件信息功能示例

本文实例讲述了Python实现的读取电脑硬件信息功能。分享给大家供大家参考,具体如下: 上学那会,老师让我用java获取电脑硬件信息,CPU, 硬盘,MAC等,那个时候感觉搞了好久。。。...

Python将string转换到float的实例方法

Python将string转换到float的实例方法

Python 如何转换string到float?简单几步,让你轻松解决。 打开软件,新建python项目,如图所示 右键菜单中创建.py文件,如图所示 步骤中文件输入代码如下...