blob: b0b002f0e1827313a9558dc57815a42c0db54ee3 [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
105 *fileobj* is the file object to monitor.
106 *events* is a bitwise mask of events to monitor.
107 *data* is an opaque object.
108
109 This returns a new :class:`SelectorKey` instance, or raises a
110 :exc:`ValueError` in case of invalid event mask or file descriptor, or
111 :exc:`KeyError` if the file object is already registered.
112
113 .. method:: unregister(fileobj)
114
115 Unregister a file object from selection, removing it from monitoring. A
116 file object shall be unregistered prior to being closed.
117
118 *fileobj* must be a file object previously registered.
119
120 This returns the associated :class:`SelectorKey` instance, or raises a
121 :exc:`KeyError` if the file object is not registered.
122
123 .. method:: modify(fileobj, events, data=None)
124
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500125 Change a registered file object's monitored events or attached data.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200126
127 This is equivalent to :meth:`BaseSelector.unregister(fileobj)` followed
128 by :meth:`BaseSelector.register(fileobj, events, data)`, except that it
129 can be implemented more efficiently.
130
131 This returns a new :class:`SelectorKey` instance, or raises a
132 :exc:`ValueError` in case of invalid event mask or file descriptor, or
133 :exc:`KeyError` if the file object is not registered.
134
135 .. method:: select(timeout=None)
136
137 Wait until some registered file objects become ready, or the timeout
138 expires.
139
140 If ``timeout > 0``, this specifies the maximum wait time, in seconds.
141 If ``timeout <= 0``, the call won't block, and will report the currently
142 ready file objects.
143 If *timeout* is ``None``, the call will block until a monitored file object
144 becomes ready.
145
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500146 This returns a list of ``(key, events)`` tuples, one for each ready file
Charles-François Natali243d8d82013-09-04 19:02:49 +0200147 object.
148
149 *key* is the :class:`SelectorKey` instance corresponding to a ready file
150 object.
151 *events* is a bitmask of events ready on this file object.
152
Charles-François Natali837a6e02013-12-01 13:23:48 +0100153 .. note::
154 This method can return before any file object becomes ready or the
155 timeout has elapsed if the current process receives a signal: in this
156 case, an empty list will be returned.
157
Charles-François Natali243d8d82013-09-04 19:02:49 +0200158 .. method:: close()
159
160 Close the selector.
161
162 This must be called to make sure that any underlying resource is freed.
163 The selector shall not be used once it has been closed.
164
165 .. method:: get_key(fileobj)
166
Andrew Kuchlingb3931d22013-11-22 16:15:28 -0500167 Return the key associated with a registered file object.
Charles-François Natali243d8d82013-09-04 19:02:49 +0200168
169 This returns the :class:`SelectorKey` instance associated to this file
170 object, or raises :exc:`KeyError` if the file object is not registered.
171
Charles-François Natali4574b492013-10-30 20:31:04 +0100172 .. method:: get_map()
173
174 Return a mapping of file objects to selector keys.
175
176 This returns a :class:`~collections.abc.Mapping` instance mapping
177 registered file objects to their associated :class:`SelectorKey`
178 instance.
179
Charles-François Natali243d8d82013-09-04 19:02:49 +0200180
181.. class:: DefaultSelector()
182
183 The default selector class, using the most efficient implementation
184 available on the current platform. This should be the default choice for
185 most users.
186
187
188.. class:: SelectSelector()
189
190 :func:`select.select`-based selector.
191
192
193.. class:: PollSelector()
194
195 :func:`select.poll`-based selector.
196
197
198.. class:: EpollSelector()
199
200 :func:`select.epoll`-based selector.
201
202 .. method:: fileno()
203
204 This returns the file descriptor used by the underlying
205 :func:`select.epoll` object.
206
207
208.. class:: KqueueSelector()
209
210 :func:`select.kqueue`-based selector.
211
212 .. method:: fileno()
213
214 This returns the file descriptor used by the underlying
215 :func:`select.kqueue` object.
216
217
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800218Examples
219--------
Charles-François Natali243d8d82013-09-04 19:02:49 +0200220
Guido van Rossum8519e5a2013-11-29 14:51:18 -0800221Here is a simple echo server implementation::
222
223 import selectors
224 import socket
225
226 sel = selectors.DefaultSelector()
227
228 def accept(sock, mask):
229 conn, addr = sock.accept() # Should be ready
230 print('accepted', conn, 'from', addr)
231 conn.setblocking(False)
232 sel.register(conn, selectors.EVENT_READ, read)
233
234 def read(conn, mask):
235 data = conn.recv(1000) # Should be ready
236 if data:
237 print('echoing', repr(data), 'to', conn)
238 conn.send(data) # Hope it won't block
239 else:
240 print('closing', conn)
241 sel.unregister(conn)
242 conn.close()
243
244 sock = socket.socket()
245 sock.bind(('localhost', 1234))
246 sock.listen(100)
247 sock.setblocking(False)
248 sel.register(sock, selectors.EVENT_READ, accept)
249
250 while True:
251 events = sel.select()
252 for key, mask in events:
253 callback = key.data
254 callback(key.fileobj, mask)