Python select模块学习

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

  通常用法:python

    # 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.socket

  模块定义了:ide

    exception:函数

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

    functions:操作系统

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

      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

相关文章
相关标签/搜索