blob: 98377c890f024220b4e652608cd56e21de6b86ac [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
48 +-- KqueueSelector
49
50
51In the following, *events* is a bitwise mask indicating which I/O events should
52be waited for on a given file object. It can be a combination of the constants
53below:
54
55 +-----------------------+-----------------------------------------------+
56 | Constant | Meaning |
57 +=======================+===============================================+
58 | :const:`EVENT_READ` | Available for read |
59 +-----------------------+-----------------------------------------------+
60 | :const:`EVENT_WRITE` | Available for write |
61 +-----------------------+-----------------------------------------------+
62
63
64.. class:: SelectorKey
65
66 A :class:`SelectorKey` is a :class:`~collections.namedtuple` used to
67 associate a file object to its underlying file decriptor, selected event
68 mask and attached data. It is returned by several :class:`BaseSelector`
69 methods.
70
71 .. attribute:: fileobj
72
73 File object registered.
74
75 .. attribute:: fd
76
77 Underlying file descriptor.
78
79 .. attribute:: events
80
Andrew Kuchlingb3931d22013-11-22 16:15:28 -050081 Events that must be waited for on this file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +020082
83 .. attribute:: data
84
85 Optional opaque data associated to this file object: for example, this
Andrew Kuchlingb3931d22013-11-22 16:15:28 -050086 could be used to store a per-client session ID.
Charles-François Natali243d8d82013-09-04 19:02:49 +020087
88
89.. class:: BaseSelector
90
91 A :class:`BaseSelector` is used to wait for I/O event readiness on multiple
92 file objects. It supports file stream registration, unregistration, and a
93 method to wait for I/O events on those streams, with an optional timeout.
94 It's an abstract base class, so cannot be instantiated. Use
95 :class:`DefaultSelector` instead, or one of :class:`SelectSelector`,
96 :class:`KqueueSelector` etc. if you want to specifically use an
97 implementation, and your platform supports it.
98 :class:`BaseSelector` and its concrete implementations support the
99 :term:`context manager` protocol.
100
101 .. method:: register(fileobj, events, data=None)
102
103 Register a file object for selection, monitoring it for I/O events.
104
Guido van Rossum9710ff02013-12-07 15:57:01 -0800105 *fileobj* is the file object to monitor. It may either be an integer
106 file descriptor or an object with a ``fileno()`` method.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200107 *events* is a bitwise mask of events to monitor.
108 *data* is an opaque object.
109
110 This returns a new :class:`SelectorKey` instance, or raises a
111 :exc:`ValueError` in case of invalid event mask or file descriptor, or
112 :exc:`KeyError` if the file object is already registered.
113
114 .. method:: unregister(fileobj)
115
116 Unregister a file object from selection, removing it from monitoring. A
117 file object shall be unregistered prior to being closed.
118
119 *fileobj* must be a file object previously registered.
120
121 This returns the associated :class:`SelectorKey` instance, or raises a
Guido van Rossum9710ff02013-12-07 15:57:01 -0800122 :exc:`KeyError` if *fileobj* is not registered. It will raise
123 :exc:`ValueError` if *fileobj* is invalid (e.g. it has no ``fileno()``
124 method or its ``fileno()`` method has an invalid return value).
Charles-François Natali243d8d82013-09-04 19:02:49 +0200125
126 .. method:: modify(fileobj, events, data=None)
127
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500128 Change a registered file object's monitored events or attached data.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200129
130 This is equivalent to :meth:`BaseSelector.unregister(fileobj)` followed
131 by :meth:`BaseSelector.register(fileobj, events, data)`, except that it
132 can be implemented more efficiently.
133
134 This returns a new :class:`SelectorKey` instance, or raises a
135 :exc:`ValueError` in case of invalid event mask or file descriptor, or
136 :exc:`KeyError` if the file object is not registered.
137
138 .. method:: select(timeout=None)
139
140 Wait until some registered file objects become ready, or the timeout
141 expires.
142
143 If ``timeout > 0``, this specifies the maximum wait time, in seconds.
144 If ``timeout <= 0``, the call won't block, and will report the currently
145 ready file objects.
146 If *timeout* is ``None``, the call will block until a monitored file object
147 becomes ready.
148
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500149 This returns a list of ``(key, events)`` tuples, one for each ready file
Charles-François Natali243d8d82013-09-04 19:02:49 +0200150 object.
151
152 *key* is the :class:`SelectorKey` instance corresponding to a ready file
153 object.
154 *events* is a bitmask of events ready on this file object.
155
Charles-François Natali837a6e02013-12-01 13:23:48 +0100156 .. note::
157 This method can return before any file object becomes ready or the
158 timeout has elapsed if the current process receives a signal: in this
159 case, an empty list will be returned.
160
Charles-François Natali243d8d82013-09-04 19:02:49 +0200161 .. method:: close()
162
163 Close the selector.
164
165 This must be called to make sure that any underlying resource is freed.
166 The selector shall not be used once it has been closed.
167
168 .. method:: get_key(fileobj)
169
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500170 Return the key associated with a registered file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200171
172 This returns the :class:`SelectorKey` instance associated to this file
173 object, or raises :exc:`KeyError` if the file object is not registered.
174
Charles-François Natali4574b492013-10-30 20:31:04 +0100175 .. method:: get_map()
176
177 Return a mapping of file objects to selector keys.
178
179 This returns a :class:`~collections.abc.Mapping` instance mapping
180 registered file objects to their associated :class:`SelectorKey`
181 instance.
182
Charles-François Natali243d8d82013-09-04 19:02:49 +0200183
184.. class:: DefaultSelector()
185
186 The default selector class, using the most efficient implementation
187 available on the current platform. This should be the default choice for
188 most users.
189
190
191.. class:: SelectSelector()
192
193 :func:`select.select`-based selector.
194
195
196.. class:: PollSelector()
197
198 :func:`select.poll`-based selector.
199
200
201.. class:: EpollSelector()
202
203 :func:`select.epoll`-based selector.
204
205 .. method:: fileno()
206
207 This returns the file descriptor used by the underlying
208 :func:`select.epoll` object.
209
210
211.. class:: KqueueSelector()
212
213 :func:`select.kqueue`-based selector.
214
215 .. method:: fileno()
216
217 This returns the file descriptor used by the underlying
218 :func:`select.kqueue` object.
219
220
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800221Examples
222--------
Charles-François Natali243d8d82013-09-04 19:02:49 +0200223
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800224Here is a simple echo server implementation::
225
226 import selectors
227 import socket
228
229 sel = selectors.DefaultSelector()
230
231 def accept(sock, mask):
232 conn, addr = sock.accept() # Should be ready
233 print('accepted', conn, 'from', addr)
234 conn.setblocking(False)
235 sel.register(conn, selectors.EVENT_READ, read)
236
237 def read(conn, mask):
238 data = conn.recv(1000) # Should be ready
239 if data:
240 print('echoing', repr(data), 'to', conn)
241 conn.send(data) # Hope it won't block
242 else:
243 print('closing', conn)
244 sel.unregister(conn)
245 conn.close()
246
247 sock = socket.socket()
248 sock.bind(('localhost', 1234))
249 sock.listen(100)
250 sock.setblocking(False)
251 sel.register(sock, selectors.EVENT_READ, accept)
252
253 while True:
254 events = sel.select()
255 for key, mask in events:
256 callback = key.data
257 callback(key.fileobj, mask)