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

相关文章

Django如何配置mysql数据库

Django如何配置mysql数据库

Django项目默认使用sqlite 数据库,但是我想用mysql数据库,应该如何配置呢。 Django连接mysql数据库的操作,是通过根模块的配置实现的,在项目根模块的配置文件set...

python SQLAlchemy 中的Engine详解

python SQLAlchemy 中的Engine详解

先看这张图,这是从官方网站扒下来的。 Engine 翻译过来就是引擎的意思,汽车通过引擎来驱动,而 SQLAlchemy 是通过 Engine 来驱动,Engine 维护了一个连接池(...

python实现一行输入多个值和一行输出多个值的例子

python实现一行输入多个值和一行输出多个值的例子

注:以下内容在python3中操作 一. 一行输入多个值 a,b = input().split() #此时得到的a和b的类型均为字符串,以空格为分隔符 a,b = input()....

使用python实现链表操作

使用python实现链表操作

一、概念梳理 链表是计算机科学里面应用应用最广泛的数据结构之一。它是最简单的数据结构之一,同时也是比较高阶的数据结构(例如棧、环形缓冲和队列) 简单的说,一个列表就是单数据通过索引集合在...

Python实现串口通信(pyserial)过程解析

pyserial模块封装了对串口的访问,兼容各种平台。 安装 pip insatll pyserial 初始化 简单初始化示例 import serial ser = se...