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中json格式数据输出的简单实现方法

主要使用json模块,直接导入import json即可。 小例子如下: #coding=UTF-8 import json info={} info["code"]=...

python tkinter基本属性详解

python tkinter基本属性详解

1.外形尺寸 尺寸单位:只用默认的像素或者其他字符类的值!,不要用英寸毫米之类的内容。 btn = tkinter.Button(root,text = '按钮') # 设置按钮尺寸...

numpy中loadtxt 的用法详解

numpy中有两个函数可以用来读取文件,主要是txt文件, 下面主要来介绍这两个函数的用法 第一个是loadtxt, 其一般用法为 numpy.loadtxt(fname, dtype=...

Python中关于使用模块的基础知识

 一个模块可以在逻辑上组织Python代码。将相关的代码到一个模块中,使代码更容易理解和使用。模块是可以绑定和借鉴任意命名属性的Python对象。 简单地说,一个模块是由Pyt...

详解Python中的元组与逻辑运算符

详解Python中的元组与逻辑运算符

Python元组 元组是另一个数据类型,类似于List(列表)。 元组用"()"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。 #!/usr/bin/python...