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