blob: d27eb4bd8289edaeb0c2b6cba90ec7a46de31751 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Victor Stinner9592edb2014-02-02 15:03:02 +01003.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +01004
Victor Stinneraea82292014-07-08 23:42:38 +02005Base Event Loop
6===============
Victor Stinnerea3183f2013-12-03 01:08:00 +01007
8The event loop is the central execution device provided by :mod:`asyncio`.
9It provides multiple facilities, amongst which:
10
Eli Benderskyb73c8332014-02-09 06:07:47 -080011* Registering, executing and cancelling delayed calls (timeouts).
Victor Stinnerea3183f2013-12-03 01:08:00 +010012
Victor Stinner9592edb2014-02-02 15:03:02 +010013* Creating client and server :ref:`transports <asyncio-transport>` for various
Eli Benderskyb73c8332014-02-09 06:07:47 -080014 kinds of communication.
Victor Stinnerea3183f2013-12-03 01:08:00 +010015
Eli Bendersky136fea22014-02-09 06:55:58 -080016* Launching subprocesses and the associated :ref:`transports
17 <asyncio-transport>` for communication with an external program.
Victor Stinnerea3183f2013-12-03 01:08:00 +010018
Eli Benderskyb73c8332014-02-09 06:07:47 -080019* Delegating costly function calls to a pool of threads.
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Victor Stinneraea82292014-07-08 23:42:38 +020021.. class:: BaseEventLoop
Eli Bendersky136fea22014-02-09 06:55:58 -080022
Victor Stinneraea82292014-07-08 23:42:38 +020023 Base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
Victor Stinner83704962015-02-25 14:24:15 +010025 This class is :ref:`not thread safe <asyncio-multithreading>`.
26
Victor Stinnerea3183f2013-12-03 01:08:00 +010027Run an event loop
28-----------------
29
30.. method:: BaseEventLoop.run_forever()
31
32 Run until :meth:`stop` is called.
33
34.. method:: BaseEventLoop.run_until_complete(future)
35
Victor Stinner99c2ab42013-12-03 19:17:25 +010036 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010037
Victor Stinner530ef2f2014-07-08 12:39:10 +020038 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
39 :func:`async`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010040
41 Return the Future's result, or raise its exception.
42
43.. method:: BaseEventLoop.is_running()
44
45 Returns running status of event loop.
46
Victor Stinnerafbf8272013-12-03 02:05:42 +010047.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010048
49 Stop running the event loop.
50
51 Every callback scheduled before :meth:`stop` is called will run.
Andrew Svetlovca4f3432014-07-24 11:36:33 +030052 Callbacks scheduled after :meth:`stop` is called will not run.
53 However, those callbacks will run if :meth:`run_forever` is called
54 again later.
Victor Stinnerea3183f2013-12-03 01:08:00 +010055
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020056.. method:: BaseEventLoop.is_closed()
57
58 Returns ``True`` if the event loop was closed.
59
60 .. versionadded:: 3.4.2
61
Victor Stinnerea3183f2013-12-03 01:08:00 +010062.. method:: BaseEventLoop.close()
63
Terry Jan Reedy9ff41802014-07-24 02:59:02 -040064 Close the event loop. The loop must not be running.
Victor Stinnerea3183f2013-12-03 01:08:00 +010065
66 This clears the queues and shuts down the executor, but does not wait for
67 the executor to finish.
68
69 This is idempotent and irreversible. No other methods should be called after
70 this one.
71
Victor Stinner8464c242014-11-28 13:15:41 +010072.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +010073
74Calls
75-----
76
Victor Stinner8464c242014-11-28 13:15:41 +010077Most :mod:`asyncio` functions don't accept keywords. If you want to pass
78keywords to your callback, use :func:`functools.partial`. For example,
79``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
80``print("Hello", flush=True)``.
81
82.. note::
83 :func:`functools.partial` is better than ``lambda`` functions, because
84 :mod:`asyncio` can inspect :func:`functools.partial` object to display
85 parameters in debug mode, whereas ``lambda`` functions have a poor
86 representation.
87
Victor Stinnerea3183f2013-12-03 01:08:00 +010088.. method:: BaseEventLoop.call_soon(callback, \*args)
89
Victor Stinner4d5115c2014-12-15 17:50:55 +010090 Arrange for a callback to be called as soon as possible. The callback is
91 called after :meth:`call_soon` returns, when control returns to the event
92 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +010093
94 This operates as a FIFO queue, callbacks are called in the order in
95 which they are registered. Each callback will be called exactly once.
96
97 Any positional arguments after the callback will be passed to the
98 callback when it is called.
99
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500100 An instance of :class:`asyncio.Handle` is returned.
101
Victor Stinner8464c242014-11-28 13:15:41 +0100102 :ref:`Use functools.partial to pass keywords to the callback
103 <asyncio-pass-keywords>`.
104
Victor Stinnerea3183f2013-12-03 01:08:00 +0100105.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
106
107 Like :meth:`call_soon`, but thread safe.
108
Victor Stinner83704962015-02-25 14:24:15 +0100109 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
110 section of the documentation.
111
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
Victor Stinner45b27ed2014-02-01 02:36:43 +0100113.. _asyncio-delayed-calls:
114
Victor Stinnerea3183f2013-12-03 01:08:00 +0100115Delayed calls
116-------------
117
118The event loop has its own internal clock for computing timeouts.
119Which clock is used depends on the (platform-specific) event loop
120implementation; ideally it is a monotonic clock. This will generally be
121a different clock than :func:`time.time`.
122
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100123.. note::
124
125 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
126
Victor Stinner45b27ed2014-02-01 02:36:43 +0100127
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128.. method:: BaseEventLoop.call_later(delay, callback, *args)
129
130 Arrange for the *callback* to be called after the given *delay*
131 seconds (either an int or float).
132
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500133 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100134
135 *callback* will be called exactly once per call to :meth:`call_later`.
136 If two callbacks are scheduled for exactly the same time, it is
137 undefined which will be called first.
138
139 The optional positional *args* will be passed to the callback when it
140 is called. If you want the callback to be called with some named
141 arguments, use a closure or :func:`functools.partial`.
142
Victor Stinner8464c242014-11-28 13:15:41 +0100143 :ref:`Use functools.partial to pass keywords to the callback
144 <asyncio-pass-keywords>`.
145
Victor Stinnerea3183f2013-12-03 01:08:00 +0100146.. method:: BaseEventLoop.call_at(when, callback, *args)
147
148 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200149 *when* (an int or float), using the same time reference as
150 :meth:`BaseEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151
152 This method's behavior is the same as :meth:`call_later`.
153
Victor Stinner8464c242014-11-28 13:15:41 +0100154 :ref:`Use functools.partial to pass keywords to the callback
155 <asyncio-pass-keywords>`.
156
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157.. method:: BaseEventLoop.time()
158
159 Return the current time, as a :class:`float` value, according to the
160 event loop's internal clock.
161
Victor Stinner3e09e322013-12-03 01:22:06 +0100162.. seealso::
163
164 The :func:`asyncio.sleep` function.
165
Victor Stinnerea3183f2013-12-03 01:08:00 +0100166
Victor Stinner530ef2f2014-07-08 12:39:10 +0200167Coroutines
168----------
169
170.. method:: BaseEventLoop.create_task(coro)
171
172 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
173 a future. Return a :class:`Task` object.
174
175 Third-party event loops can use their own subclass of :class:`Task` for
176 interoperability. In this case, the result type is a subclass of
177 :class:`Task`.
178
Victor Stinner337e03f2014-08-11 01:11:13 +0200179 This method was added in Python 3.4.2. Use the :func:`async` function to
180 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200181
182 .. versionadded:: 3.4.2
183
184
Victor Stinnerea3183f2013-12-03 01:08:00 +0100185Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100186--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100187
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100188.. coroutinemethod:: BaseEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100189
190 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100191 *port*: socket family :py:data:`~socket.AF_INET` or
192 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
193 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
194 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100195
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500196 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100197 establish the connection in the background. When successful, the
198 coroutine returns a ``(transport, protocol)`` pair.
199
200 The chronological synopsis of the underlying operation is as follows:
201
Victor Stinner9592edb2014-02-02 15:03:02 +0100202 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100203 is created to represent it.
204
205 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100206 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100207
208 #. The protocol instance is tied to the transport, and its
209 :meth:`connection_made` method is called.
210
211 #. The coroutine returns successfully with the ``(transport, protocol)``
212 pair.
213
214 The created transport is an implementation-dependent bidirectional stream.
215
216 .. note::
217 *protocol_factory* can be any kind of callable, not necessarily
218 a class. For example, if you want to use a pre-created
219 protocol instance, you can pass ``lambda: my_protocol``.
220
221 Options allowing to change how the connection is created:
222
223 * *ssl*: if given and not false, a SSL/TLS transport is created
224 (by default a plain TCP transport is created). If *ssl* is
225 a :class:`ssl.SSLContext` object, this context is used to create
226 the transport; if *ssl* is :const:`True`, a context with some
227 unspecified default settings is used.
228
Berker Peksag9c1dba22014-09-28 00:00:58 +0300229 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100230
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231 * *server_hostname*, is only for use together with *ssl*,
232 and sets or overrides the hostname that the target server's certificate
233 will be matched against. By default the value of the *host* argument
234 is used. If *host* is empty, there is no default and you must pass a
235 value for *server_hostname*. If *server_hostname* is an empty
236 string, hostname matching is disabled (which is a serious security
237 risk, allowing for man-in-the-middle-attacks).
238
239 * *family*, *proto*, *flags* are the optional address family, protocol
240 and flags to be passed through to getaddrinfo() for *host* resolution.
241 If given, these should all be integers from the corresponding
242 :mod:`socket` module constants.
243
244 * *sock*, if given, should be an existing, already connected
245 :class:`socket.socket` object to be used by the transport.
246 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
247 and *local_addr* should be specified.
248
249 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
250 to bind the socket to locally. The *local_host* and *local_port*
251 are looked up using getaddrinfo(), similarly to *host* and *port*.
252
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200253 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
254
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100255 .. seealso::
256
257 The :func:`open_connection` function can be used to get a pair of
258 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
259
Victor Stinnerea3183f2013-12-03 01:08:00 +0100260
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100261.. coroutinemethod:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100262
263 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
264 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
265 socket type :py:data:`~socket.SOCK_DGRAM`.
266
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500267 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100268 establish the connection in the background. When successful, the
269 coroutine returns a ``(transport, protocol)`` pair.
270
271 See the :meth:`BaseEventLoop.create_connection` method for parameters.
272
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200273 On Windows with :class:`ProactorEventLoop`, this method is not supported.
274
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200275 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
276 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
277
Victor Stinnera6919aa2014-02-19 13:32:34 +0100278
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100279.. coroutinemethod:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100280
281 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
282 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
283 family is used to communicate between processes on the same machine
284 efficiently.
285
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500286 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100287 establish the connection in the background. When successful, the
288 coroutine returns a ``(transport, protocol)`` pair.
289
290 See the :meth:`BaseEventLoop.create_connection` method for parameters.
291
292 Availability: UNIX.
293
294
Victor Stinnerea3183f2013-12-03 01:08:00 +0100295Creating listening connections
296------------------------------
297
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100298.. coroutinemethod:: BaseEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100299
Victor Stinner33f6abe2014-10-12 20:36:04 +0200300 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
301 *host* and *port*.
302
303 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
304 contains created sockets. Use the :meth:`Server.close` method to stop the
305 server: close listening sockets.
306
307 Parameters:
308
309 * If *host* is an empty string or ``None``, all interfaces are assumed
310 and a list of multiple sockets will be returned (most likely
311 one for IPv4 and another one for IPv6).
312
313 * *family* can be set to either :data:`socket.AF_INET` or
314 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
315 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
316
317 * *flags* is a bitmask for :meth:`getaddrinfo`.
318
319 * *sock* can optionally be specified in order to use a preexisting
320 socket object. If specified, *host* and *port* should be omitted (must be
321 :const:`None`).
322
323 * *backlog* is the maximum number of queued connections passed to
324 :meth:`~socket.socket.listen` (defaults to 100).
325
326 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
327 accepted connections.
328
329 * *reuse_address* tells the kernel to reuse a local socket in
330 TIME_WAIT state, without waiting for its natural timeout to
331 expire. If not specified will automatically be set to True on
332 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
Victor Stinnerd1432092014-06-19 17:11:49 +0200334 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100335
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200336 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
337
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100338 .. seealso::
339
340 The function :func:`start_server` creates a (:class:`StreamReader`,
341 :class:`StreamWriter`) pair and calls back a function with this pair.
342
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100344.. coroutinemethod:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
Victor Stinnera6919aa2014-02-19 13:32:34 +0100346 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
347 socket family :py:data:`~socket.AF_UNIX`.
348
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100349 This method is a :ref:`coroutine <coroutine>`.
350
Victor Stinnera6919aa2014-02-19 13:32:34 +0100351 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100352
353
Victor Stinnerc1567df2014-02-08 23:22:58 +0100354Watch file descriptors
355----------------------
356
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200357On Windows with :class:`SelectorEventLoop`, only socket handles are supported
358(ex: pipe file descriptors are not supported).
359
360On Windows with :class:`ProactorEventLoop`, these methods are not supported.
361
Victor Stinnerc1567df2014-02-08 23:22:58 +0100362.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
363
364 Start watching the file descriptor for read availability and then call the
365 *callback* with specified arguments.
366
Victor Stinner8464c242014-11-28 13:15:41 +0100367 :ref:`Use functools.partial to pass keywords to the callback
368 <asyncio-pass-keywords>`.
369
Victor Stinnerc1567df2014-02-08 23:22:58 +0100370.. method:: BaseEventLoop.remove_reader(fd)
371
372 Stop watching the file descriptor for read availability.
373
374.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
375
376 Start watching the file descriptor for write availability and then call the
377 *callback* with specified arguments.
378
Victor Stinner8464c242014-11-28 13:15:41 +0100379 :ref:`Use functools.partial to pass keywords to the callback
380 <asyncio-pass-keywords>`.
381
Victor Stinnerc1567df2014-02-08 23:22:58 +0100382.. method:: BaseEventLoop.remove_writer(fd)
383
384 Stop watching the file descriptor for write availability.
385
Victor Stinner04e6df32014-10-11 16:16:27 +0200386The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
387example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
388the file descriptor of a socket.
389
Victor Stinnerc1567df2014-02-08 23:22:58 +0100390
391Low-level socket operations
392---------------------------
393
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100394.. coroutinemethod:: BaseEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100395
396 Receive data from the socket. The return value is a bytes object
397 representing the data received. The maximum amount of data to be received
398 at once is specified by *nbytes*.
399
Victor Stinnerd84fd732014-08-26 01:01:59 +0200400 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
401 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200402
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500403 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100404
405 .. seealso::
406
407 The :meth:`socket.socket.recv` method.
408
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100409.. coroutinemethod:: BaseEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100410
411 Send data to the socket. The socket must be connected to a remote socket.
412 This method continues to send data from *data* until either all data has
413 been sent or an error occurs. ``None`` is returned on success. On error,
414 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500415 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100416
Victor Stinnerd84fd732014-08-26 01:01:59 +0200417 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
418 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200419
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500420 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100421
422 .. seealso::
423
424 The :meth:`socket.socket.sendall` method.
425
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100426.. coroutinemethod:: BaseEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100427
428 Connect to a remote socket at *address*.
429
Victor Stinner1b0580b2014-02-13 09:24:37 +0100430 The *address* must be already resolved to avoid the trap of hanging the
431 entire event loop when the address requires doing a DNS lookup. For
432 example, it must be an IP address, not an hostname, for
433 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
434 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
435
Victor Stinnerd84fd732014-08-26 01:01:59 +0200436 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
437 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200438
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500439 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100440
441 .. seealso::
442
443 The :meth:`BaseEventLoop.create_connection` method, the
444 :func:`open_connection` function and the :meth:`socket.socket.connect`
445 method.
446
447
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100448.. coroutinemethod:: BaseEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100449
450 Accept a connection. The socket must be bound to an address and listening
451 for connections. The return value is a pair ``(conn, address)`` where *conn*
452 is a *new* socket object usable to send and receive data on the connection,
453 and *address* is the address bound to the socket on the other end of the
454 connection.
455
Victor Stinnerec2ce092014-07-29 23:12:22 +0200456 The socket *sock* must be non-blocking.
457
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500458 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100459
460 .. seealso::
461
462 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
463 function and the :meth:`socket.socket.accept` method.
464
465
466Resolve host name
467-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100468
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100469.. coroutinemethod:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500471 This method is a :ref:`coroutine <coroutine>`, similar to
472 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100474.. coroutinemethod:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500476 This method is a :ref:`coroutine <coroutine>`, similar to
477 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100478
479
Victor Stinner984600f2014-03-25 09:40:26 +0100480Connect pipes
481-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200483On Windows with :class:`SelectorEventLoop`, these methods are not supported.
484Use :class:`ProactorEventLoop` to support pipes on Windows.
485
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100486.. coroutinemethod:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100487
Victor Stinnerd84fd732014-08-26 01:01:59 +0200488 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
490 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200491 interface. *pipe* is a :term:`file-like object <file object>`.
492 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100493 :class:`ReadTransport` interface.
494
Victor Stinnerd84fd732014-08-26 01:01:59 +0200495 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
496 non-blocking mode.
497
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500498 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100499
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100500.. coroutinemethod:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100501
502 Register write pipe in eventloop.
503
504 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200505 interface. *pipe* is :term:`file-like object <file object>`.
506 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100507 :class:`WriteTransport` interface.
508
Victor Stinnerd84fd732014-08-26 01:01:59 +0200509 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
510 non-blocking mode.
511
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500512 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100513
Victor Stinner08444382014-02-02 22:43:39 +0100514.. seealso::
515
Victor Stinner984600f2014-03-25 09:40:26 +0100516 The :meth:`BaseEventLoop.subprocess_exec` and
517 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100518
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Victor Stinner8b863482014-01-27 10:07:50 +0100520UNIX signals
521------------
522
523Availability: UNIX only.
524
525.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
526
527 Add a handler for a signal.
528
529 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
530 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
531
Victor Stinner8464c242014-11-28 13:15:41 +0100532 :ref:`Use functools.partial to pass keywords to the callback
533 <asyncio-pass-keywords>`.
534
Victor Stinner8b863482014-01-27 10:07:50 +0100535.. method:: BaseEventLoop.remove_signal_handler(sig)
536
537 Remove a handler for a signal.
538
539 Return ``True`` if a signal handler was removed, ``False`` if not.
540
541.. seealso::
542
543 The :mod:`signal` module.
544
545
Victor Stinnerea3183f2013-12-03 01:08:00 +0100546Executor
547--------
548
549Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
550pool of processes). By default, an event loop uses a thread pool executor
551(:class:`~concurrent.futures.ThreadPoolExecutor`).
552
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100553.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100554
555 Arrange for a callback to be called in the specified executor.
556
Larry Hastings3732ed22014-03-15 21:13:56 -0700557 The *executor* argument should be an :class:`~concurrent.futures.Executor`
558 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100559
Victor Stinner8464c242014-11-28 13:15:41 +0100560 :ref:`Use functools.partial to pass keywords to the callback
561 <asyncio-pass-keywords>`.
562
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500563 This method is a :ref:`coroutine <coroutine>`.
564
Victor Stinnerea3183f2013-12-03 01:08:00 +0100565.. method:: BaseEventLoop.set_default_executor(executor)
566
567 Set the default executor used by :meth:`run_in_executor`.
568
569
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500570Error Handling API
571------------------
572
573Allows to customize how exceptions are handled in the event loop.
574
575.. method:: BaseEventLoop.set_exception_handler(handler)
576
577 Set *handler* as the new event loop exception handler.
578
579 If *handler* is ``None``, the default exception handler will
580 be set.
581
582 If *handler* is a callable object, it should have a
583 matching signature to ``(loop, context)``, where ``loop``
584 will be a reference to the active event loop, ``context``
585 will be a ``dict`` object (see :meth:`call_exception_handler`
586 documentation for details about context).
587
588.. method:: BaseEventLoop.default_exception_handler(context)
589
590 Default exception handler.
591
592 This is called when an exception occurs and no exception
593 handler is set, and can be called by a custom exception
594 handler that wants to defer to the default behavior.
595
596 *context* parameter has the same meaning as in
597 :meth:`call_exception_handler`.
598
599.. method:: BaseEventLoop.call_exception_handler(context)
600
601 Call the current event loop exception handler.
602
603 *context* is a ``dict`` object containing the following keys
604 (new keys may be introduced later):
605
606 * 'message': Error message;
607 * 'exception' (optional): Exception object;
608 * 'future' (optional): :class:`asyncio.Future` instance;
609 * 'handle' (optional): :class:`asyncio.Handle` instance;
610 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
611 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
612 * 'socket' (optional): :class:`socket.socket` instance.
613
614 .. note::
615
616 Note: this method should not be overloaded in subclassed
617 event loops. For any custom exception handling, use
618 :meth:`set_exception_handler()` method.
619
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100620Debug mode
621----------
622
623.. method:: BaseEventLoop.get_debug()
624
Victor Stinner7b7120e2014-06-23 00:12:14 +0200625 Get the debug mode (:class:`bool`) of the event loop.
626
627 The default value is ``True`` if the environment variable
628 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
629 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100630
Victor Stinner64d750b2014-06-18 03:25:23 +0200631 .. versionadded:: 3.4.2
632
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100633.. method:: BaseEventLoop.set_debug(enabled: bool)
634
635 Set the debug mode of the event loop.
636
Victor Stinner64d750b2014-06-18 03:25:23 +0200637 .. versionadded:: 3.4.2
638
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100639.. seealso::
640
Victor Stinner62511fd2014-06-23 00:36:11 +0200641 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100642
Victor Stinner8c462c52014-01-24 18:11:43 +0100643Server
644------
645
Victor Stinner8ebeb032014-07-11 23:47:40 +0200646.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100647
Victor Stinner8ebeb032014-07-11 23:47:40 +0200648 Server listening on sockets.
649
650 Object created by the :meth:`BaseEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500651 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100652
653 .. method:: close()
654
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200655 Stop serving: close listening sockets and set the :attr:`sockets`
656 attribute to ``None``.
657
658 The sockets that represent existing incoming client connections are
659 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200660
661 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
662 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100663
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100664 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100665
Victor Stinner8ebeb032014-07-11 23:47:40 +0200666 Wait until the :meth:`close` method completes.
667
668 This method is a :ref:`coroutine <coroutine>`.
669
670 .. attribute:: sockets
671
672 List of :class:`socket.socket` objects the server is listening to, or
673 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100674
675
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500676Handle
677------
678
679.. class:: Handle
680
681 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
682 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
683 and :func:`BaseEventLoop.call_at`.
684
685 .. method:: cancel()
686
Victor Stinneraea82292014-07-08 23:42:38 +0200687 Cancel the call.
688
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500689
Victor Stinner6888b962014-10-11 16:15:58 +0200690Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100691-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500692
Victor Stinner3e09e322013-12-03 01:22:06 +0100693.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100694
Victor Stinner7f314ed2014-10-15 18:49:16 +0200695Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100696^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100697
Victor Stinner7f314ed2014-10-15 18:49:16 +0200698Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
699callback. The callback displays ``"Hello World"`` and then stops the event
700loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100701
702 import asyncio
703
Victor Stinner7f314ed2014-10-15 18:49:16 +0200704 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100705 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200706 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100707
708 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200709
710 # Schedule a call to hello_world()
711 loop.call_soon(hello_world, loop)
712
713 # Blocking call interrupted by loop.stop()
714 loop.run_forever()
715 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100716
Victor Stinner3e09e322013-12-03 01:22:06 +0100717.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100718
Victor Stinner6888b962014-10-11 16:15:58 +0200719 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
720 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100721
Victor Stinner8b863482014-01-27 10:07:50 +0100722
Victor Stinner7f314ed2014-10-15 18:49:16 +0200723.. _asyncio-date-callback:
724
725Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100726^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200727
728Example of callback displaying the current date every second. The callback uses
729the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
730seconds, and then stops the event loop::
731
732 import asyncio
733 import datetime
734
735 def display_date(end_time, loop):
736 print(datetime.datetime.now())
737 if (loop.time() + 1.0) < end_time:
738 loop.call_later(1, display_date, end_time, loop)
739 else:
740 loop.stop()
741
742 loop = asyncio.get_event_loop()
743
744 # Schedule the first call to display_date()
745 end_time = loop.time() + 5.0
746 loop.call_soon(display_date, end_time, loop)
747
748 # Blocking call interrupted by loop.stop()
749 loop.run_forever()
750 loop.close()
751
752.. seealso::
753
754 The :ref:`coroutine displaying the current date
755 <asyncio-date-coroutine>` example uses a :ref:`coroutine
756 <coroutine>`.
757
758
Victor Stinner04e6df32014-10-11 16:16:27 +0200759.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100760
Victor Stinner04e6df32014-10-11 16:16:27 +0200761Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100762^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200763
764Wait until a file descriptor received some data using the
765:meth:`BaseEventLoop.add_reader` method and then close the event loop::
766
767 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200768 try:
769 from socket import socketpair
770 except ImportError:
771 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200772
773 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200774 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200775 loop = asyncio.get_event_loop()
776
777 def reader():
778 data = rsock.recv(100)
779 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200780 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200781 loop.remove_reader(rsock)
782 # Stop the event loop
783 loop.stop()
784
Victor Stinner2cef3002014-10-23 22:38:46 +0200785 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200786 loop.add_reader(rsock, reader)
787
788 # Simulate the reception of data from the network
789 loop.call_soon(wsock.send, 'abc'.encode())
790
791 # Run the event loop
792 loop.run_forever()
793
794 # We are done, close sockets and the event loop
795 rsock.close()
796 wsock.close()
797 loop.close()
798
799.. seealso::
800
801 The :ref:`register an open socket to wait for data using a protocol
802 <asyncio-register-socket>` example uses a low-level protocol created by the
803 :meth:`BaseEventLoop.create_connection` method.
804
805 The :ref:`register an open socket to wait for data using streams
806 <asyncio-register-socket-streams>` example uses high-level streams
807 created by the :func:`open_connection` function in a coroutine.
808
809
810Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100811^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200812
813Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
814the :meth:`BaseEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100815
816 import asyncio
817 import functools
818 import os
819 import signal
820
821 def ask_exit(signame):
822 print("got signal %s: exit" % signame)
823 loop.stop()
824
825 loop = asyncio.get_event_loop()
826 for signame in ('SIGINT', 'SIGTERM'):
827 loop.add_signal_handler(getattr(signal, signame),
828 functools.partial(ask_exit, signame))
829
830 print("Event loop running forever, press CTRL+c to interrupt.")
831 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200832 try:
833 loop.run_forever()
834 finally:
835 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200836
837This example only works on UNIX.