selectors
select — 等待 I/O 完成
select
Added in version 3.4.
源代码: Lib/selectors.py
此模块允许高级且高效的 I/O 复用,构建于 select 模块原语。鼓励用户使用此模块取而代之,除非想要精确控制所用的 OS 级别原语。
它定义 BaseSelector 抽象基类,除了几个具体实现 ( KqueueSelector , EpollSelector …), that can be used to wait for I/O readiness notification on multiple file objects. In the following, “file object” refers to any object with a fileno() method, or a raw file descriptor. See 文件对象 .
BaseSelector
KqueueSelector
EpollSelector
fileno()
DefaultSelector is an alias to the most efficient implementation available on the current platform: this should be the default choice for most users.
DefaultSelector
注意
The type of file objects supported depends on the platform: on Windows, sockets are supported, but not pipes, whereas on Unix, both are supported (some other types may be supported as well, such as fifos or special file devices).
另请参阅
低级 I/O 复用模块。
可用性 :非 Emscripten,非 WASI。
本模块不工作 (或不可用) 于 WebAssembly 平台 wasm32-emscripten and wasm32-wasi 。见 WebAssembly 平台 了解更多信息。
wasm32-emscripten
wasm32-wasi
类层次结构:
BaseSelector +-- SelectSelector +-- PollSelector +-- EpollSelector +-- DevpollSelector +-- KqueueSelector
In the following, events is a bitwise mask indicating which I/O events should be waited for on a given file object. It can be a combination of the modules constants below:
常量 含义 selectors. EVENT_READ ¶ 可用于读取 selectors. EVENT_WRITE ¶ 可用于写入 class selectors. SelectorKey ¶ A SelectorKey 是 namedtuple used to associate a file object to its underlying file descriptor, selected event mask and attached data. It is returned by several BaseSelector 方法。 fileobj ¶ 注册文件对象。 fd ¶ 底层文件描述符。 events ¶ Events that must be waited for on this file object. data ¶ Optional opaque data associated to this file object: for example, this could be used to store a per-client session ID. class selectors. BaseSelector ¶ A BaseSelector is used to wait for I/O event readiness on multiple file objects. It supports file stream registration, unregistration, and a method to wait for I/O events on those streams, with an optional timeout. It’s an abstract base class, so cannot be instantiated. Use DefaultSelector instead, or one of SelectSelector , KqueueSelector etc. if you want to specifically use an implementation, and your platform supports it. BaseSelector and its concrete implementations support the 上下文管理器 协议。 abstractmethod register ( fileobj , events , data = None ) ¶ Register a file object for selection, monitoring it for I/O events. fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() 方法。 events is a bitwise mask of events to monitor. data is an opaque object. 这返回新的 SelectorKey 实例,或引发 ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered. abstractmethod unregister ( fileobj ) ¶ Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed. fileobj must be a file object previously registered. This returns the associated SelectorKey 实例,或引发 KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value). 修改 ( fileobj , events , data = None ) ¶ Change a registered file object’s monitored events or attached data. 这相当于 BaseSelector.unregister(fileobj) followed by BaseSelector.register(fileobj, events, data) , except that it can be implemented more efficiently. 这返回新的 SelectorKey 实例,或引发 ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered. abstractmethod select ( timeout = None ) ¶ Wait until some registered file objects become ready, or the timeout expires. 若 timeout > 0 , this specifies the maximum wait time, in seconds. If timeout <= 0 , the call won’t block, and will report the currently ready file objects. If timeout is None , the call will block until a monitored file object becomes ready. This returns a list of (key, events) tuples, one for each ready file object. key 是 SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object. 注意 This method can return before any file object becomes ready or the timeout has elapsed if the current process receives a signal: in this case, an empty list will be returned. 3.5 版改变: The selector is now retried with a recomputed timeout when interrupted by a signal if the signal handler did not raise an exception (see PEP 475 for the rationale), instead of returning an empty list of events before the timeout. close ( ) ¶ Close the selector. This must be called to make sure that any underlying resource is freed. The selector shall not be used once it has been closed. get_key ( fileobj ) ¶ Return the key associated with a registered file object. This returns the SelectorKey instance associated to this file object, or raises KeyError if the file object is not registered. abstractmethod get_map ( ) ¶ Return a mapping of file objects to selector keys. This returns a Mapping instance mapping registered file objects to their associated SelectorKey 实例。 class selectors. DefaultSelector ¶ The default selector class, using the most efficient implementation available on the current platform. This should be the default choice for most users. class selectors. SelectSelector ¶ select.select() -based selector. class selectors. PollSelector ¶ select.poll() -based selector. class selectors. EpollSelector ¶ select.epoll() -based selector. fileno ( ) ¶ This returns the file descriptor used by the underlying select.epoll() 对象。 class selectors. DevpollSelector ¶ select.devpoll() -based selector. fileno ( ) ¶ This returns the file descriptor used by the underlying select.devpoll() 对象。 Added in version 3.5. class selectors. KqueueSelector ¶ select.kqueue() -based selector. fileno ( ) ¶ This returns the file descriptor used by the underlying select.kqueue() 对象。 范例 ¶ Here is a simple echo server implementation: import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) # Should be ready if data: print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block else: print('closing', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind(('localhost', 1234)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) while True: events = sel.select() for key, mask in events: callback = key.data callback(key.fileobj, mask)
常量
含义
A SelectorKey 是 namedtuple used to associate a file object to its underlying file descriptor, selected event mask and attached data. It is returned by several BaseSelector 方法。
SelectorKey
namedtuple
注册文件对象。
底层文件描述符。
Events that must be waited for on this file object.
Optional opaque data associated to this file object: for example, this could be used to store a per-client session ID.
A BaseSelector is used to wait for I/O event readiness on multiple file objects. It supports file stream registration, unregistration, and a method to wait for I/O events on those streams, with an optional timeout. It’s an abstract base class, so cannot be instantiated. Use DefaultSelector instead, or one of SelectSelector , KqueueSelector etc. if you want to specifically use an implementation, and your platform supports it. BaseSelector and its concrete implementations support the 上下文管理器 协议。
SelectSelector
Register a file object for selection, monitoring it for I/O events.
fileobj is the file object to monitor. It may either be an integer file descriptor or an object with a fileno() 方法。 events is a bitwise mask of events to monitor. data is an opaque object.
这返回新的 SelectorKey 实例,或引发 ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered.
ValueError
KeyError
Unregister a file object from selection, removing it from monitoring. A file object shall be unregistered prior to being closed.
fileobj must be a file object previously registered.
This returns the associated SelectorKey 实例,或引发 KeyError if fileobj is not registered. It will raise ValueError if fileobj is invalid (e.g. it has no fileno() method or its fileno() method has an invalid return value).
Change a registered file object’s monitored events or attached data.
这相当于 BaseSelector.unregister(fileobj) followed by BaseSelector.register(fileobj, events, data) , except that it can be implemented more efficiently.
BaseSelector.unregister(fileobj)
BaseSelector.register(fileobj, events, data)
这返回新的 SelectorKey 实例,或引发 ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered.
Wait until some registered file objects become ready, or the timeout expires.
若 timeout > 0 , this specifies the maximum wait time, in seconds. If timeout <= 0 , the call won’t block, and will report the currently ready file objects. If timeout is None , the call will block until a monitored file object becomes ready.
timeout > 0
timeout <= 0
None
This returns a list of (key, events) tuples, one for each ready file object.
(key, events)
key 是 SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object.
This method can return before any file object becomes ready or the timeout has elapsed if the current process receives a signal: in this case, an empty list will be returned.
3.5 版改变: The selector is now retried with a recomputed timeout when interrupted by a signal if the signal handler did not raise an exception (see PEP 475 for the rationale), instead of returning an empty list of events before the timeout.
Close the selector.
This must be called to make sure that any underlying resource is freed. The selector shall not be used once it has been closed.
Return the key associated with a registered file object.
This returns the SelectorKey instance associated to this file object, or raises KeyError if the file object is not registered.
Return a mapping of file objects to selector keys.
This returns a Mapping instance mapping registered file objects to their associated SelectorKey 实例。
Mapping
The default selector class, using the most efficient implementation available on the current platform. This should be the default choice for most users.
select.select() -based selector.
select.select()
select.poll() -based selector.
select.poll()
select.epoll() -based selector.
select.epoll()
This returns the file descriptor used by the underlying select.epoll() 对象。
select.devpoll() -based selector.
select.devpoll()
This returns the file descriptor used by the underlying select.devpoll() 对象。
Added in version 3.5.
select.kqueue() -based selector.
select.kqueue()
This returns the file descriptor used by the underlying select.kqueue() 对象。
Here is a simple echo server implementation:
import selectors import socket sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1000) # Should be ready if data: print('echoing', repr(data), 'to', conn) conn.send(data) # Hope it won't block else: print('closing', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind(('localhost', 1234)) sock.listen(100) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, accept) while True: events = sel.select() for key, mask in events: callback = key.data callback(key.fileobj, mask)
signal — 为异步事件设置处理程序
signal
键入搜索术语或模块、类、函数名称。