blob: f6ef24b6ae6de55645da1e69442550f891b1bb7b [file] [log] [blame]
Charles-François Natali243d8d82013-09-04 19:02:49 +02001:mod:`selectors` -- High-level I/O multiplexing
2===============================================
3
4.. module:: selectors
5 :synopsis: High-level I/O multiplexing.
6
7.. versionadded:: 3.4
8
9
10Introduction
11------------
12
13This module allows high-level and efficient I/O multiplexing, built upon the
14:mod:`select` module primitives. Users are encouraged to use this module
15instead, unless they want precise control over the OS-level primitives used.
16
17It defines a :class:`BaseSelector` abstract base class, along with several
18concrete implementations (:class:`KqueueSelector`, :class:`EpollSelector`...),
19that can be used to wait for I/O readiness notification on multiple file
20objects. In the following, "file object" refers to any object with a
21:meth:`fileno()` method, or a raw file descriptor. See :term:`file object`.
22
23:class:`DefaultSelector` is an alias to the most efficient implementation
24available on the current platform: this should be the default choice for most
25users.
26
27.. note::
28 The type of file objects supported depends on the platform: on Windows,
29 sockets are supported, but not pipes, whereas on Unix, both are supported
30 (some other types may be supported as well, such as fifos or special file
31 devices).
32
33.. seealso::
34
35 :mod:`select`
36 Low-level I/O multiplexing module.
37
38
39Classes
40-------
41
42Classes hierarchy::
43
44 BaseSelector
45 +-- SelectSelector
46 +-- PollSelector
47 +-- EpollSelector
Giampaolo Rodola'f97e8292014-03-20 21:43:41 +010048 +-- DevpollSelector
Charles-François Natali243d8d82013-09-04 19:02:49 +020049 +-- KqueueSelector
50
51
52In the following, *events* is a bitwise mask indicating which I/O events should
53be waited for on a given file object. It can be a combination of the constants
54below:
55
56 +-----------------------+-----------------------------------------------+
57 | Constant | Meaning |
58 +=======================+===============================================+
59 | :const:`EVENT_READ` | Available for read |
60 +-----------------------+-----------------------------------------------+
61 | :const:`EVENT_WRITE` | Available for write |
62 +-----------------------+-----------------------------------------------+
63
64
65.. class:: SelectorKey
66
67 A :class:`SelectorKey` is a :class:`~collections.namedtuple` used to
68 associate a file object to its underlying file decriptor, selected event
69 mask and attached data. It is returned by several :class:`BaseSelector`
70 methods.
71
72 .. attribute:: fileobj
73
74 File object registered.
75
76 .. attribute:: fd
77
78 Underlying file descriptor.
79
80 .. attribute:: events
81
Andrew Kuchlingb3931d22013-11-22 16:15:28 -050082 Events that must be waited for on this file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +020083
84 .. attribute:: data
85
86 Optional opaque data associated to this file object: for example, this
Andrew Kuchlingb3931d22013-11-22 16:15:28 -050087 could be used to store a per-client session ID.
Charles-François Natali243d8d82013-09-04 19:02:49 +020088
89
90.. class:: BaseSelector
91
92 A :class:`BaseSelector` is used to wait for I/O event readiness on multiple
93 file objects. It supports file stream registration, unregistration, and a
94 method to wait for I/O events on those streams, with an optional timeout.
95 It's an abstract base class, so cannot be instantiated. Use
96 :class:`DefaultSelector` instead, or one of :class:`SelectSelector`,
97 :class:`KqueueSelector` etc. if you want to specifically use an
98 implementation, and your platform supports it.
99 :class:`BaseSelector` and its concrete implementations support the
100 :term:`context manager` protocol.
101
102 .. method:: register(fileobj, events, data=None)
103
104 Register a file object for selection, monitoring it for I/O events.
105
Guido van Rossum9710ff02013-12-07 15:57:01 -0800106 *fileobj* is the file object to monitor. It may either be an integer
107 file descriptor or an object with a ``fileno()`` method.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200108 *events* is a bitwise mask of events to monitor.
109 *data* is an opaque object.
110
111 This returns a new :class:`SelectorKey` instance, or raises a
112 :exc:`ValueError` in case of invalid event mask or file descriptor, or
113 :exc:`KeyError` if the file object is already registered.
114
115 .. method:: unregister(fileobj)
116
117 Unregister a file object from selection, removing it from monitoring. A
118 file object shall be unregistered prior to being closed.
119
120 *fileobj* must be a file object previously registered.
121
122 This returns the associated :class:`SelectorKey` instance, or raises a
Guido van Rossum9710ff02013-12-07 15:57:01 -0800123 :exc:`KeyError` if *fileobj* is not registered. It will raise
124 :exc:`ValueError` if *fileobj* is invalid (e.g. it has no ``fileno()``
125 method or its ``fileno()`` method has an invalid return value).
Charles-François Natali243d8d82013-09-04 19:02:49 +0200126
127 .. method:: modify(fileobj, events, data=None)
128
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500129 Change a registered file object's monitored events or attached data.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200130
131 This is equivalent to :meth:`BaseSelector.unregister(fileobj)` followed
132 by :meth:`BaseSelector.register(fileobj, events, data)`, except that it
133 can be implemented more efficiently.
134
135 This returns a new :class:`SelectorKey` instance, or raises a
136 :exc:`ValueError` in case of invalid event mask or file descriptor, or
137 :exc:`KeyError` if the file object is not registered.
138
139 .. method:: select(timeout=None)
140
141 Wait until some registered file objects become ready, or the timeout
142 expires.
143
144 If ``timeout > 0``, this specifies the maximum wait time, in seconds.
145 If ``timeout <= 0``, the call won't block, and will report the currently
146 ready file objects.
147 If *timeout* is ``None``, the call will block until a monitored file object
148 becomes ready.
149
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500150 This returns a list of ``(key, events)`` tuples, one for each ready file
Charles-François Natali243d8d82013-09-04 19:02:49 +0200151 object.
152
153 *key* is the :class:`SelectorKey` instance corresponding to a ready file
154 object.
155 *events* is a bitmask of events ready on this file object.
156
Charles-François Natali837a6e02013-12-01 13:23:48 +0100157 .. note::
158 This method can return before any file object becomes ready or the
159 timeout has elapsed if the current process receives a signal: in this
160 case, an empty list will be returned.
161
Victor Stinnerb3101732015-03-31 12:08:09 +0200162 .. versionchanged:: 3.5
163 The selector is now retried with a recomputed timeout when interrupted
164 by a signal if the signal handler did not raise an exception (see
165 :pep:`475` for the rationale), instead of returning an empty list
166 of events before the timeout.
167
Charles-François Natali243d8d82013-09-04 19:02:49 +0200168 .. method:: close()
169
170 Close the selector.
171
172 This must be called to make sure that any underlying resource is freed.
173 The selector shall not be used once it has been closed.
174
175 .. method:: get_key(fileobj)
176
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500177 Return the key associated with a registered file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200178
179 This returns the :class:`SelectorKey` instance associated to this file
180 object, or raises :exc:`KeyError` if the file object is not registered.
181
Charles-François Natali4574b492013-10-30 20:31:04 +0100182 .. method:: get_map()
183
184 Return a mapping of file objects to selector keys.
185
186 This returns a :class:`~collections.abc.Mapping` instance mapping
187 registered file objects to their associated :class:`SelectorKey`
188 instance.
189
Charles-François Natali243d8d82013-09-04 19:02:49 +0200190
191.. class:: DefaultSelector()
192
193 The default selector class, using the most efficient implementation
194 available on the current platform. This should be the default choice for
195 most users.
196
197
198.. class:: SelectSelector()
199
200 :func:`select.select`-based selector.
201
202
203.. class:: PollSelector()
204
205 :func:`select.poll`-based selector.
206
207
208.. class:: EpollSelector()
209
210 :func:`select.epoll`-based selector.
211
212 .. method:: fileno()
213
214 This returns the file descriptor used by the underlying
215 :func:`select.epoll` object.
216
Giampaolo Rodola'f97e8292014-03-20 21:43:41 +0100217.. class:: DevpollSelector()
218
219 :func:`select.devpoll`-based selector.
220
221 .. method:: fileno()
222
223 This returns the file descriptor used by the underlying
224 :func:`select.devpoll` object.
225
Georg Brandl77605cb2014-03-24 09:06:33 +0100226 .. versionadded:: 3.5
Charles-François Natali243d8d82013-09-04 19:02:49 +0200227
228.. class:: KqueueSelector()
229
230 :func:`select.kqueue`-based selector.
231
232 .. method:: fileno()
233
234 This returns the file descriptor used by the underlying
235 :func:`select.kqueue` object.
236
237
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800238Examples
239--------
Charles-François Natali243d8d82013-09-04 19:02:49 +0200240
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800241Here is a simple echo server implementation::
242
243 import selectors
244 import socket
245
246 sel = selectors.DefaultSelector()
247
248 def accept(sock, mask):
249 conn, addr = sock.accept() # Should be ready
250 print('accepted', conn, 'from', addr)
251 conn.setblocking(False)
252 sel.register(conn, selectors.EVENT_READ, read)
253
254 def read(conn, mask):
255 data = conn.recv(1000) # Should be ready
256 if data:
257 print('echoing', repr(data), 'to', conn)
258 conn.send(data) # Hope it won't block
259 else:
260 print('closing', conn)
261 sel.unregister(conn)
262 conn.close()
263
264 sock = socket.socket()
265 sock.bind(('localhost', 1234))
266 sock.listen(100)
267 sock.setblocking(False)
268 sel.register(sock, selectors.EVENT_READ, accept)
269
270 while True:
271 events = sel.select()
272 for key, mask in events:
273 callback = key.data
274 callback(key.fileobj, mask)