blob: 8bd9e1ce2e2dcce09f8b4cc385075ca18d7f87c9 [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
Charles-François Natali243d8d82013-09-04 19:02:49 +0200162 .. method:: close()
163
164 Close the selector.
165
166 This must be called to make sure that any underlying resource is freed.
167 The selector shall not be used once it has been closed.
168
169 .. method:: get_key(fileobj)
170
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500171 Return the key associated with a registered file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200172
173 This returns the :class:`SelectorKey` instance associated to this file
174 object, or raises :exc:`KeyError` if the file object is not registered.
175
Charles-François Natali4574b492013-10-30 20:31:04 +0100176 .. method:: get_map()
177
178 Return a mapping of file objects to selector keys.
179
180 This returns a :class:`~collections.abc.Mapping` instance mapping
181 registered file objects to their associated :class:`SelectorKey`
182 instance.
183
Charles-François Natali243d8d82013-09-04 19:02:49 +0200184
185.. class:: DefaultSelector()
186
187 The default selector class, using the most efficient implementation
188 available on the current platform. This should be the default choice for
189 most users.
190
191
192.. class:: SelectSelector()
193
194 :func:`select.select`-based selector.
195
196
197.. class:: PollSelector()
198
199 :func:`select.poll`-based selector.
200
201
202.. class:: EpollSelector()
203
204 :func:`select.epoll`-based selector.
205
206 .. method:: fileno()
207
208 This returns the file descriptor used by the underlying
209 :func:`select.epoll` object.
210
Giampaolo Rodola'f97e8292014-03-20 21:43:41 +0100211.. class:: DevpollSelector()
212
213 :func:`select.devpoll`-based selector.
214
215 .. method:: fileno()
216
217 This returns the file descriptor used by the underlying
218 :func:`select.devpoll` object.
219
Georg Brandl77605cb2014-03-24 09:06:33 +0100220 .. versionadded:: 3.5
Charles-François Natali243d8d82013-09-04 19:02:49 +0200221
222.. class:: KqueueSelector()
223
224 :func:`select.kqueue`-based selector.
225
226 .. method:: fileno()
227
228 This returns the file descriptor used by the underlying
229 :func:`select.kqueue` object.
230
231
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800232Examples
233--------
Charles-François Natali243d8d82013-09-04 19:02:49 +0200234
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800235Here is a simple echo server implementation::
236
237 import selectors
238 import socket
239
240 sel = selectors.DefaultSelector()
241
242 def accept(sock, mask):
243 conn, addr = sock.accept() # Should be ready
244 print('accepted', conn, 'from', addr)
245 conn.setblocking(False)
246 sel.register(conn, selectors.EVENT_READ, read)
247
248 def read(conn, mask):
249 data = conn.recv(1000) # Should be ready
250 if data:
251 print('echoing', repr(data), 'to', conn)
252 conn.send(data) # Hope it won't block
253 else:
254 print('closing', conn)
255 sel.unregister(conn)
256 conn.close()
257
258 sock = socket.socket()
259 sock.bind(('localhost', 1234))
260 sock.listen(100)
261 sock.setblocking(False)
262 sel.register(sock, selectors.EVENT_READ, accept)
263
264 while True:
265 events = sel.select()
266 for key, mask in events:
267 callback = key.data
268 callback(key.fileobj, mask)