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

相关文章

Pycharm设置界面全黑的方法

win7 pycharm设置界面全黑色方法: 1.设置默认PyCharm解析器: 操作如下: Python–>Preferences–>Project Interprete...

Python图像的增强处理操作示例【基于ImageEnhance类】

Python图像的增强处理操作示例【基于ImageEnhance类】

本文实例讲述了Python图像的增强处理操作。分享给大家供大家参考,具体如下: python中PIL模块中有一个叫做ImageEnhance的类,该类专门用于图像的增强处理,不仅可以增强...

使用python实现离散时间傅里叶变换的方法

使用python实现离散时间傅里叶变换的方法

我们经常使用傅里叶变换来计算数字信号的频谱,进而分析数字信号,离散时间傅里叶变换的公式为: 可是自己动手实现一遍才是最好的学习。 在数字分析里面,傅里叶变换默认等时间间隔采样,不需...

python实现随机漫步算法

本文实例为大家分享了python实现随机漫步的具体代码,供大家参考,具体内容如下 编写randomwalk类 from random import choice class ra...

python 机器学习之支持向量机非线性回归SVR模型

python 机器学习之支持向量机非线性回归SVR模型

本文介绍了python 支持向量机非线性回归SVR模型,废话不多说,具体如下: import numpy as np import matplotlib.pyplot as plt...