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程序设计有所帮助。

相关文章

selenium+python自动化测试之环境搭建

selenium+python自动化测试之环境搭建

最近由于公司有一个向谷歌网站上传文件的需求,需要进行web的自动化测试,选择了selenium这个自动化测试框架,以前没有接触过这门技术,所以研究了一下,使用python来实现自动化脚本...

Python 获取新浪微博的最新公共微博实例分享

API: statuses/public_timeline  返回最新的200条公共微博,返回结果非完全实时 CODE: #!/usr/bin/python # -*-...

Jacobi迭代算法的Python实现详解

import numpy as np import time 1.1 Jacobi迭代算法 def Jacobi_tensor_V2(A,b,Delta,m,n,M): st...

探究python中open函数的使用

探究python中open函数的使用

最近,开始学习python的开发,遇到了一点文件操作的问题,探究一下open函数的使用。 一、open()的函数原型 open(file, mode=‘r', buffering=-1,...

浅谈Python里面小数点精度的控制

要求较小的精度 round()内置方法 这个是使用最多的,刚看了round()的使用解释,也不是很容易懂。round()不是简单的四舍五入的处理方式。 For the built-in...