码迷,mamicode.com
首页 > 编程语言 > 详细

Python select模块学习

时间:2015-08-02 23:11:33      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

  select 是常用的异步socket 处理方法

  一般用法:

    # iwtd,owtd,ewtd 分别为需要异步处理的读socket队列, 写socket队列(一般不用), 和错误socket队列, 返回事件的读写和错误socket队列

il,ol,el = select(iwtd,owtd,ewtd[,timeout])
for sock in il:
    #read the sock
for sock in ol:
    #...
for sock in el:
    #handle errors

  select 和 poll 都是比较低级的函数, 用起来比较麻烦, 如果使用异步socket编程,可以使用twisted

  1.模块的功能主要是等待I/O完成, 提供在大多数操作系统上对select() 和 poll()函数的调用, 在Linux 2.5+上可以调用epoll(),在BSD上可以调用kqueue() , 在Windows上, 模块只能工作在socket上, 在其他操作系统上, 它还可以工作在其他文件类型上(如在Unix上, 可以工作在pipes上).它不能被用来判断一个普通文件在最后一次读操作之后是否有grown.

  模块定义了:

    exception:

      select.error(): 当错误发生时抛出,  会像C函数的perror()一样打印错误编号和描述字符串

    functions:

      select.epoll([sizehint=-1]): 返回一个edge polling 对象, 可以用来作为Edge or Level Triggered interface for I/O  events.

      select.poll(): 不是在所有系统上都支持, 返回一个polling 对象, 可以用来支持registering and unregistering file descriptors, 然后polling them for I/O events.

      select.kqueue(): 只支持BSD, 返回一个kernel queue object.

      select.kevent(ident,filter=KQ_FILTER_READ,flags=KQ_EV_ADD,fflags=0,data=0,udata=0): 只支持BSD,返回一个kernel queue object.

      select.select(rlist,wlist,xlist[,timeout]): 这是一个straightforward interface to Unix select()系统调用, 前3个参数是一串可等待对象, 表示代表文件描述符的整数或者带有一个名为fileno()的无参方法返回的同样的整数;

        参数:  1.rlist: 等待直到读准备好; 2.wlist: 等待直到写操作准备好; 3.xlist: 等待一个"exceptional condition" ;      允许空序列, 但是如果3个参数都为空的列表的话, 在Unix上可以, 但在Windows上不行, 与平台相关 . 当timeout参数被设定之后, 函数将blocks 知道至少一个文件描述符 is ready, 值为0 表示 a poll and never block.

        返回值: triple of list of object that are ready. subsets of the first three arguments. 当time-out reached, 但还没有file descriptor ready, 返回 three empty lists.

        Among the acceptable object types in the sequence are python file object, like sys.stdin or objects returned by open() or os.popen()(这个命令可以用来执行系统调用, 相当于os.system(), 用法: os.popen("ping 192.168.1.1")) .

    Constant:

      select.PIPE_BUF: ...

 

  2. Edge and Level Trigger Polling(epoll) Object

    技术分享

  epoll.close() : close the control file descriptor of the epoll object.  

  epoll.fileno(): return the file descriptor number of the control fd

  epoll.fromfd(fd): create an epoll object from a given file descriptor

  epoll.register(fd[,eventmask]) : register a fd descriptor with the epoll object.

  更多信息参考: https://docs.python.org/2.7/library/select.html?highlight=select#module-select

  

       

 

Python select模块学习

标签:

原文地址:http://www.cnblogs.com/roger9567/p/4695233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!