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

相关文章

用virtualenv建立多个Python独立虚拟开发环境

用virtualenv建立多个Python独立虚拟开发环境

本文为大家分享了virtualenv建立多个Python独立虚拟开发环境,供大家参考,具体内容如下 1、安装virtualenv: pip install virtualenv 2...

Python使用Phantomjs截屏网页的方法

实例如下所示: #!/usr/bin/python # -*- coding:utf8 -*- from selenium import webdriver import os d...

python的scikit-learn将特征转成one-hot特征的方法

如下所示: enc = OneHotEncoder(categorical_features=np.array([0,1,2]),n_values=[5,4,2]) enc.f...

浅谈pytorch、cuda、python的版本对齐问题

在使用深度学习模型训练的过程中,工具的准备也算是一个良好的开端吧。熟话说完事开头难,磨刀不误砍柴工,先把前期的问题搞通了,能为后期节省不少精力。 以pytorch工具为例: pytorc...

Python基础教程之异常详解

Python基础教程之异常详解

一、摘要 Python使用被称为异常 的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运...