Chinaunix首页 | 论坛 | 博客
  • 博客访问: 93704
  • 博文数量: 15
  • 博客积分: 416
  • 博客等级: 一等列兵
  • 技术积分: 169
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-15 15:03
文章分类

全部博文(15)

文章存档

2012年(12)

2006年(3)

我的朋友

分类: Python/Ruby

2012-07-28 11:02:51

在Python中使用select与poll比起在C中使用简单得多。select函数的参数是3个列表,包含整数文件描述符,或者带有可返回文件描述符的fileno()方法对象。第一个参数是需要等待输入的对象,第二个指定等待输出的对象,第三个参数指定异常情况的对象。第四个参数则为设置超时时间,是一个浮点数。指定以秒为单位的超时值。select函数将会返回一组文件描述符,包括输入,输出以及异常。

在linux下利用select实现多路IO的文件复制程序:


点击(此处)折叠或打开

  1. #!/usr/bin/env python


  2. import select
  3. #导入select模块

  4. BLKSIZE=8192

  5. def readwrite(fromfd,tofd):
  6.     readbuf = fromfd.read(BLKSIZE)
  7.     if readbuf:
  8.         tofd.write(readbuf)
  9.         tofd.flush()
  10.     return len(readbuf)

  11. def copy2file(fromfd1,tofd1,fromfd2,tofd2):
  12.         ''' using select to choice fds'''
  13.     totalbytes=0
  14.         if not (fromfd1 or fromfd2 or tofd1 or tofd2) :
  15. #检查所有文件描述符是否合法
  16.                 return 0
  17.     while True:
  18. #开始利用select对输入所有输入的文件描述符进行监视
  19.         rs,ws,es = select.select([fromfd1,fromfd2],[],[])
  20.         for r in rs:

  21.             if r is fromfd1:
  22. #当第一个文件描述符可读时,读入数据
  23.                 bytesread = readwrite(fromfd1,tofd1)            
  24.                 totalbytes += bytesread
  25.             if r is fromfd2:
  26.                 bytesread = readwrite(fromfd2,tofd2)
  27.                 totalbytes += bytesread
  28.         if (bytesread <= 0):
  29.             break
  30.     return totalbytes
  31. def main():
  32.     
  33.     fromfd1 = open("/etc/fstab","r")
  34.     fromfd2 = open("/etc/passwd","r")

  35.     tofd1 = open("/root/fstab","w+")
  36.     tofd2 = open("/root/passwd","w+")

  37.     totalbytes = copy2file(fromfd1,tofd1,fromfd2,tofd2)
  38.     
  39.     print "Number of bytes copied %d\n" % totalbytes
  40.     return 0
  41.     


  42. if __name__=="__main__":
  43.     main()

阅读(5162) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

raygtr2015-11-12 16:05:18

olivetree123:这里并没有体现出异步,只有多路复用,实际上 select() 是阻塞的,不能实现异步

这里可能是描述上有些误解,这个只是模拟异步IO,而且select有一个timeout参数,当它设置为0的时候它就不是阻塞的了,这样就可以实现异步了,特别是你在多线程的情况下。

回复 | 举报

olivetree1232015-10-09 10:48:06

这里并没有体现出异步,只有多路复用,实际上 select() 是阻塞的,不能实现异步