selectors — High-level I/O multiplexing

New in version 3.4.版本3.4中新增。

Source code: Lib/selectors.py


Introduction介绍

This module allows high-level and efficient I/O multiplexing, built upon the select module primitives. 该模块允许基于select模块原语的高级高效I/O复用。Users are encouraged to use this module instead, unless they want precise control over the OS-level primitives used.鼓励用户改用此模块,除非他们希望对所使用的操作系统级原语进行精确控制。

It defines a BaseSelector abstract base class, along with several concrete implementations (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 file object.

DefaultSelector is an alias to the most efficient implementation available on the current platform: this should be the default choice for most users.是当前平台上最有效的实现的别名:这应该是大多数用户的默认选择。

Note

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).支持的文件对象类型取决于平台:在Windows上,支持套接字,但不支持管道,而在Unix上,两者都受支持(也可能支持一些其他类型,如fifo或特殊文件设备)。

See also

select

Low-level I/O multiplexing module.

Classes

Classes hierarchy:类层次结构:

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. 在下文中,events是一个按位掩码,指示应在给定文件对象上等待哪些I/O事件。It can be a combination of the modules constants below:它可以是以下模块常数的组合:

Constant常数

Meaning

EVENT_READ

Available for read可供阅读

EVENT_WRITE

Available for write可用于写入

classselectors.SelectorKey

A SelectorKey is a namedtuple used to associate a file object to its underlying file descriptor, selected event mask and attached data. It is returned by several BaseSelector methods.

fileobj

File object registered.已注册文件对象。

fd

Underlying file descriptor.基础文件描述符。

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.

classselectors.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 context manager protocol.

abstractmethodregister(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() method. events is a bitwise mask of events to monitor. data is an opaque object.

This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is already registered.

abstractmethodunregister(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 instance, or raises a 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).

modify(fileobj, events, data=None)

Change a registered file object’s monitored events or attached data.

This is equivalent to BaseSelector.unregister(fileobj)() followed by BaseSelector.register(fileobj, events, data)(), except that it can be implemented more efficiently.

This returns a new SelectorKey instance, or raises a ValueError in case of invalid event mask or file descriptor, or KeyError if the file object is not registered.

abstractmethodselect(timeout=None)

Wait until some registered file objects become ready, or the timeout expires.

If 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, events)元组列表,每个就绪文件对象对应一个元组。

key is the SelectorKey instance corresponding to a ready file object. events is a bitmask of events ready on this file object.

Note

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.

Changed in version 3.5:版本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.这将返回与此文件对象关联的SelectorKey实例,如果文件对象未注册,则引发KeyError

abstractmethodget_map()

Return a mapping of file objects to selector keys.返回文件对象到选择器键的映射。

This returns a Mapping instance mapping registered file objects to their associated SelectorKey instance.

classselectors.DefaultSelector

The default selector class, using the most efficient implementation available on the current platform. This should be the default choice for most users.

classselectors.SelectSelector

select.select()-based selector.

classselectors.PollSelector

select.poll()-based selector.

classselectors.EpollSelector

select.epoll()-based selector.

fileno()

This returns the file descriptor used by the underlying select.epoll() object.这将返回底层select.epoll()对象使用的文件描述符。

classselectors.DevpollSelector

select.devpoll()-based selector.

fileno()

This returns the file descriptor used by the underlying select.devpoll() object.

New in version 3.5.版本3.5中新增。

classselectors.KqueueSelector

select.kqueue()-based selector.

fileno()

This returns the file descriptor used by the underlying select.kqueue() object.

Examples

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)