Debian Codegraph @

Doc/library/asyncio-eventloop.rst

raw
1 .. currentmodule:: asyncio
2
3
4 .. _asyncio-event-loop:
5
6 ==========
7 Event Loop
8 ==========
9
10 **Source code:** :source:`Lib/asyncio/events.py`,
11 :source:`Lib/asyncio/base_events.py`
12
13 ------------------------------------
14
15 .. rubric:: Preface
16
17 The event loop is the core of every asyncio application.
18 Event loops run asynchronous tasks and callbacks, perform network
19 IO operations, and run subprocesses.
20
21 Application developers should typically use the high-level asyncio functions,
22 such as :func:`asyncio.run`, and should rarely need to reference the loop
23 object or call its methods. This section is intended mostly for authors
24 of lower-level code, libraries, and frameworks, who need finer control over
25 the event loop behavior.
26
27 .. rubric:: Obtaining the Event Loop
28
29 The following low-level functions can be used to get, set, or create
30 an event loop:
31
32 .. function:: get_running_loop()
33
34 Return the running event loop in the current OS thread.
35
36 Raise a :exc:`RuntimeError` if there is no running event loop.
37
38 This function can only be called from a coroutine or a callback.
39
40 .. versionadded:: 3.7
41
42 .. function:: get_event_loop()
43
44 Get the current event loop.
45
46 When called from a coroutine or a callback (e.g. scheduled with
47 call_soon or similar API), this function will always return the
48 running event loop.
49
50 If there is no running event loop set, the function will return
51 the result of the ``get_event_loop_policy().get_event_loop()`` call.
52
53 Because this function has rather complex behavior (especially
54 when custom event loop policies are in use), using the
55 :func:`get_running_loop` function is preferred to :func:`get_event_loop`
56 in coroutines and callbacks.
57
58 As noted above, consider using the higher-level :func:`asyncio.run` function,
59 instead of using these lower level functions to manually create and close an
60 event loop.
61
62 .. deprecated:: 3.12
63 Deprecation warning is emitted if there is no current event loop.
64 In some future Python release this will become an error.
65
66 .. function:: set_event_loop(loop)
67
68 Set *loop* as the current event loop for the current OS thread.
69
70 .. function:: new_event_loop()
71
72 Create and return a new event loop object.
73
74 Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`,
75 and :func:`new_event_loop` functions can be altered by
76 :ref:`setting a custom event loop policy <asyncio-policies>`.
77
78
79 .. rubric:: Contents
80
81 This documentation page contains the following sections:
82
83 * The `Event Loop Methods`_ section is the reference documentation of
84 the event loop APIs;
85
86 * The `Callback Handles`_ section documents the :class:`Handle` and
87 :class:`TimerHandle` instances which are returned from scheduling
88 methods such as :meth:`loop.call_soon` and :meth:`loop.call_later`;
89
90 * The `Server Objects`_ section documents types returned from
91 event loop methods like :meth:`loop.create_server`;
92
93 * The `Event Loop Implementations`_ section documents the
94 :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;
95
96 * The `Examples`_ section showcases how to work with some event
97 loop APIs.
98
99
100 .. _asyncio-event-loop-methods:
101
102 Event Loop Methods
103 ==================
104
105 Event loops have **low-level** APIs for the following:
106
107 .. contents::
108 :depth: 1
109 :local:
110
111
112 Running and stopping the loop
113 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
114
115 .. method:: loop.run_until_complete(future)
116
117 Run until the *future* (an instance of :class:`Future`) has
118 completed.
119
120 If the argument is a :ref:`coroutine object <coroutine>` it
121 is implicitly scheduled to run as a :class:`asyncio.Task`.
122
123 Return the Future's result or raise its exception.
124
125 .. method:: loop.run_forever()
126
127 Run the event loop until :meth:`stop` is called.
128
129 If :meth:`stop` is called before :meth:`run_forever` is called,
130 the loop will poll the I/O selector once with a timeout of zero,
131 run all callbacks scheduled in response to I/O events (and
132 those that were already scheduled), and then exit.
133
134 If :meth:`stop` is called while :meth:`run_forever` is running,
135 the loop will run the current batch of callbacks and then exit.
136 Note that new callbacks scheduled by callbacks will not run in this
137 case; instead, they will run the next time :meth:`run_forever` or
138 :meth:`run_until_complete` is called.
139
140 .. method:: loop.stop()
141
142 Stop the event loop.
143
144 .. method:: loop.is_running()
145
146 Return ``True`` if the event loop is currently running.
147
148 .. method:: loop.is_closed()
149
150 Return ``True`` if the event loop was closed.
151
152 .. method:: loop.close()
153
154 Close the event loop.
155
156 The loop must not be running when this function is called.
157 Any pending callbacks will be discarded.
158
159 This method clears all queues and shuts down the executor, but does
160 not wait for the executor to finish.
161
162 This method is idempotent and irreversible. No other methods
163 should be called after the event loop is closed.
164
165 .. method:: loop.shutdown_asyncgens()
166 :async:
167
168 Schedule all currently open :term:`asynchronous generator` objects to
169 close with an :meth:`~agen.aclose` call. After calling this method,
170 the event loop will issue a warning if a new asynchronous generator
171 is iterated. This should be used to reliably finalize all scheduled
172 asynchronous generators.
173
174 Note that there is no need to call this function when
175 :func:`asyncio.run` is used.
176
177 Example::
178
179 try:
180 loop.run_forever()
181 finally:
182 loop.run_until_complete(loop.shutdown_asyncgens())
183 loop.close()
184
185 .. versionadded:: 3.6
186
187 .. method:: loop.shutdown_default_executor(timeout=None)
188 :async:
189
190 Schedule the closure of the default executor and wait for it to join all of
191 the threads in the :class:`~concurrent.futures.ThreadPoolExecutor`.
192 Once this method has been called,
193 using the default executor with :meth:`loop.run_in_executor`
194 will raise a :exc:`RuntimeError`.
195
196 The *timeout* parameter specifies the amount of time
197 (in :class:`float` seconds) the executor will be given to finish joining.
198 With the default, ``None``,
199 the executor is allowed an unlimited amount of time.
200
201 If the *timeout* is reached, a :exc:`RuntimeWarning` is emitted
202 and the default executor is terminated
203 without waiting for its threads to finish joining.
204
205 .. note::
206
207 Do not call this method when using :func:`asyncio.run`,
208 as the latter handles default executor shutdown automatically.
209
210 .. versionadded:: 3.9
211
212 .. versionchanged:: 3.12
213 Added the *timeout* parameter.
214
215 Scheduling callbacks
216 ^^^^^^^^^^^^^^^^^^^^
217
218 .. method:: loop.call_soon(callback, *args, context=None)
219
220 Schedule the *callback* :term:`callback` to be called with
221 *args* arguments at the next iteration of the event loop.
222
223 Return an instance of :class:`asyncio.Handle`,
224 which can be used later to cancel the callback.
225
226 Callbacks are called in the order in which they are registered.
227 Each callback will be called exactly once.
228
229 The optional keyword-only *context* argument specifies a
230 custom :class:`contextvars.Context` for the *callback* to run in.
231 Callbacks use the current context when no *context* is provided.
232
233 Unlike :meth:`call_soon_threadsafe`, this method is not thread-safe.
234
235 .. method:: loop.call_soon_threadsafe(callback, *args, context=None)
236
237 A thread-safe variant of :meth:`call_soon`. When scheduling callbacks from
238 another thread, this function *must* be used, since :meth:`call_soon` is not
239 thread-safe.
240
241 This function is safe to be called from a reentrant context or signal handler,
242 however, it is not safe or fruitful to use the returned handle in such contexts.
243
244 Raises :exc:`RuntimeError` if called on a loop that's been closed.
245 This can happen on a secondary thread when the main application is
246 shutting down.
247
248 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
249 section of the documentation.
250
251 .. versionchanged:: 3.7
252 The *context* keyword-only parameter was added. See :pep:`567`
253 for more details.
254
255 .. _asyncio-pass-keywords:
256
257 .. note::
258
259 Most :mod:`asyncio` scheduling functions don't allow passing
260 keyword arguments. To do that, use :func:`functools.partial`::
261
262 # will schedule "print("Hello", flush=True)"
263 loop.call_soon(
264 functools.partial(print, "Hello", flush=True))
265
266 Using partial objects is usually more convenient than using lambdas,
267 as asyncio can render partial objects better in debug and error
268 messages.
269
270
271 .. _asyncio-delayed-calls:
272
273 Scheduling delayed callbacks
274 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
275
276 Event loop provides mechanisms to schedule callback functions
277 to be called at some point in the future. Event loop uses monotonic
278 clocks to track time.
279
280
281 .. method:: loop.call_later(delay, callback, *args, context=None)
282
283 Schedule *callback* to be called after the given *delay*
284 number of seconds (can be either an int or a float).
285
286 An instance of :class:`asyncio.TimerHandle` is returned which can
287 be used to cancel the callback.
288
289 *callback* will be called exactly once. If two callbacks are
290 scheduled for exactly the same time, the order in which they
291 are called is undefined.
292
293 The optional positional *args* will be passed to the callback when
294 it is called. If you want the callback to be called with keyword
295 arguments use :func:`functools.partial`.
296
297 An optional keyword-only *context* argument allows specifying a
298 custom :class:`contextvars.Context` for the *callback* to run in.
299 The current context is used when no *context* is provided.
300
301 .. note::
302
303 For performance, callbacks scheduled with :meth:`loop.call_later`
304 may run up to one clock-resolution early (see
305 ``time.get_clock_info('monotonic').resolution``).
306
307 .. versionchanged:: 3.7
308 The *context* keyword-only parameter was added. See :pep:`567`
309 for more details.
310
311 .. versionchanged:: 3.8
312 In Python 3.7 and earlier with the default event loop implementation,
313 the *delay* could not exceed one day.
314 This has been fixed in Python 3.8.
315
316 .. method:: loop.call_at(when, callback, *args, context=None)
317
318 Schedule *callback* to be called at the given absolute timestamp
319 *when* (an int or a float), using the same time reference as
320 :meth:`loop.time`.
321
322 This method's behavior is the same as :meth:`call_later`.
323
324 An instance of :class:`asyncio.TimerHandle` is returned which can
325 be used to cancel the callback.
326
327 .. note::
328
329 For performance, callbacks scheduled with :meth:`loop.call_at`
330 may run up to one clock-resolution early (see
331 ``time.get_clock_info('monotonic').resolution``).
332
333 .. versionchanged:: 3.7
334 The *context* keyword-only parameter was added. See :pep:`567`
335 for more details.
336
337 .. versionchanged:: 3.8
338 In Python 3.7 and earlier with the default event loop implementation,
339 the difference between *when* and the current time could not exceed
340 one day. This has been fixed in Python 3.8.
341
342 .. method:: loop.time()
343
344 Return the current time, as a :class:`float` value, according to
345 the event loop's internal monotonic clock.
346
347 .. note::
348 .. versionchanged:: 3.8
349 In Python 3.7 and earlier timeouts (relative *delay* or absolute *when*)
350 should not exceed one day. This has been fixed in Python 3.8.
351
352 .. seealso::
353
354 The :func:`asyncio.sleep` function.
355
356
357 Creating Futures and Tasks
358 ^^^^^^^^^^^^^^^^^^^^^^^^^^
359
360 .. method:: loop.create_future()
361
362 Create an :class:`asyncio.Future` object attached to the event loop.
363
364 This is the preferred way to create Futures in asyncio. This lets
365 third-party event loops provide alternative implementations of
366 the Future object (with better performance or instrumentation).
367
368 .. versionadded:: 3.5.2
369
370 .. method:: loop.create_task(coro, *, name=None, context=None, **kwargs)
371
372 Schedule the execution of :ref:`coroutine <coroutine>` *coro*.
373 Return a :class:`Task` object.
374
375 Third-party event loops can use their own subclass of :class:`Task`
376 for interoperability. In this case, the result type is a subclass
377 of :class:`Task`.
378
379 The full function signature is largely the same as that of the
380 :class:`Task` constructor (or factory) - all of the keyword arguments to
381 this function are passed through to that interface, except *name*,
382 or *context* if it is ``None``.
383
384 If the *name* argument is provided and not ``None``, it is set as
385 the name of the task using :meth:`Task.set_name`.
386
387 An optional keyword-only *context* argument allows specifying a
388 custom :class:`contextvars.Context` for the *coro* to run in.
389 The current context copy is created when no *context* is provided.
390
391 .. versionchanged:: 3.8
392 Added the *name* parameter.
393
394 .. versionchanged:: 3.11
395 Added the *context* parameter.
396
397 .. versionchanged:: 3.13.3
398 Added ``kwargs`` which passes on arbitrary extra parameters, including ``name`` and ``context``.
399
400 .. versionchanged:: 3.13.4
401 Rolled back the change that passes on *name* and *context* (if it is None),
402 while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).
403
404 .. method:: loop.set_task_factory(factory)
405
406 Set a task factory that will be used by
407 :meth:`loop.create_task`.
408
409 If *factory* is ``None`` the default task factory will be set.
410 Otherwise, *factory* must be a *callable* with the signature matching
411 ``(loop, coro, **kwargs)``, where *loop* is a reference to the active
412 event loop, and *coro* is a coroutine object. The callable
413 must pass on all *kwargs*, and return a :class:`asyncio.Task`-compatible object.
414
415 .. versionchanged:: 3.13.3
416 Required that all *kwargs* are passed on to :class:`asyncio.Task`.
417
418 .. versionchanged:: 3.13.4
419 *name* is no longer passed to task factories. *context* is no longer passed
420 to task factories if it is ``None``.
421
422 .. method:: loop.get_task_factory()
423
424 Return a task factory or ``None`` if the default one is in use.
425
426
427 Opening network connections
428 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
429
430 .. method:: loop.create_connection(protocol_factory, \
431 host=None, port=None, *, ssl=None, \
432 family=0, proto=0, flags=0, sock=None, \
433 local_addr=None, server_hostname=None, \
434 ssl_handshake_timeout=None, \
435 ssl_shutdown_timeout=None, \
436 happy_eyeballs_delay=None, interleave=None, \
437 all_errors=False)
438 :async:
439
440 Open a streaming transport connection to a given
441 address specified by *host* and *port*.
442
443 The socket family can be either :py:const:`~socket.AF_INET` or
444 :py:const:`~socket.AF_INET6` depending on *host* (or the *family*
445 argument, if provided).
446
447 The socket type will be :py:const:`~socket.SOCK_STREAM`.
448
449 *protocol_factory* must be a callable returning an
450 :ref:`asyncio protocol <asyncio-protocol>` implementation.
451
452 This method will try to establish the connection in the background.
453 When successful, it returns a ``(transport, protocol)`` pair.
454
455 The chronological synopsis of the underlying operation is as follows:
456
457 #. The connection is established and a :ref:`transport <asyncio-transport>`
458 is created for it.
459
460 #. *protocol_factory* is called without arguments and is expected to
461 return a :ref:`protocol <asyncio-protocol>` instance.
462
463 #. The protocol instance is coupled with the transport by calling its
464 :meth:`~BaseProtocol.connection_made` method.
465
466 #. A ``(transport, protocol)`` tuple is returned on success.
467
468 The created transport is an implementation-dependent bidirectional
469 stream.
470
471 Other arguments:
472
473 * *ssl*: if given and not false, a SSL/TLS transport is created
474 (by default a plain TCP transport is created). If *ssl* is
475 a :class:`ssl.SSLContext` object, this context is used to create
476 the transport; if *ssl* is :const:`True`, a default context returned
477 from :func:`ssl.create_default_context` is used.
478
479 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
480
481 * *server_hostname* sets or overrides the hostname that the target
482 server's certificate will be matched against. Should only be passed
483 if *ssl* is not ``None``. By default the value of the *host* argument
484 is used. If *host* is empty, there is no default and you must pass a
485 value for *server_hostname*. If *server_hostname* is an empty
486 string, hostname matching is disabled (which is a serious security
487 risk, allowing for potential man-in-the-middle attacks).
488
489 * *family*, *proto*, *flags* are the optional address family, protocol
490 and flags to be passed through to getaddrinfo() for *host* resolution.
491 If given, these should all be integers from the corresponding
492 :mod:`socket` module constants.
493
494 * *happy_eyeballs_delay*, if given, enables Happy Eyeballs for this
495 connection. It should
496 be a floating-point number representing the amount of time in seconds
497 to wait for a connection attempt to complete, before starting the next
498 attempt in parallel. This is the "Connection Attempt Delay" as defined
499 in :rfc:`8305`. A sensible default value recommended by the RFC is ``0.25``
500 (250 milliseconds).
501
502 * *interleave* controls address reordering when a host name resolves to
503 multiple IP addresses.
504 If ``0`` or unspecified, no reordering is done, and addresses are
505 tried in the order returned by :meth:`getaddrinfo`. If a positive integer
506 is specified, the addresses are interleaved by address family, and the
507 given integer is interpreted as "First Address Family Count" as defined
508 in :rfc:`8305`. The default is ``0`` if *happy_eyeballs_delay* is not
509 specified, and ``1`` if it is.
510
511 * *sock*, if given, should be an existing, already connected
512 :class:`socket.socket` object to be used by the transport.
513 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*,
514 *happy_eyeballs_delay*, *interleave*
515 and *local_addr* should be specified.
516
517 .. note::
518
519 The *sock* argument transfers ownership of the socket to the
520 transport created. To close the socket, call the transport's
521 :meth:`~asyncio.BaseTransport.close` method.
522
523 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
524 to bind the socket locally. The *local_host* and *local_port*
525 are looked up using ``getaddrinfo()``, similarly to *host* and *port*.
526
527 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds
528 to wait for the TLS handshake to complete before aborting the connection.
529 ``60.0`` seconds if ``None`` (default).
530
531 * *ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown
532 to complete before aborting the connection. ``30.0`` seconds if ``None``
533 (default).
534
535 * *all_errors* determines what exceptions are raised when a connection cannot
536 be created. By default, only a single ``Exception`` is raised: the first
537 exception if there is only one or all errors have same message, or a single
538 ``OSError`` with the error messages combined. When ``all_errors`` is ``True``,
539 an ``ExceptionGroup`` will be raised containing all exceptions (even if there
540 is only one).
541
542
543 .. versionchanged:: 3.5
544
545 Added support for SSL/TLS in :class:`ProactorEventLoop`.
546
547 .. versionchanged:: 3.6
548
549 The socket option :ref:`socket.TCP_NODELAY <socket-unix-constants>` is set by default
550 for all TCP connections.
551
552 .. versionchanged:: 3.7
553
554 Added the *ssl_handshake_timeout* parameter.
555
556 .. versionchanged:: 3.8
557
558 Added the *happy_eyeballs_delay* and *interleave* parameters.
559
560 Happy Eyeballs Algorithm: Success with Dual-Stack Hosts.
561 When a server's IPv4 path and protocol are working, but the server's
562 IPv6 path and protocol are not working, a dual-stack client
563 application experiences significant connection delay compared to an
564 IPv4-only client. This is undesirable because it causes the
565 dual-stack client to have a worse user experience. This document
566 specifies requirements for algorithms that reduce this user-visible
567 delay and provides an algorithm.
568
569 For more information: https://datatracker.ietf.org/doc/html/rfc6555
570
571 .. versionchanged:: 3.11
572
573 Added the *ssl_shutdown_timeout* parameter.
574
575 .. versionchanged:: 3.12
576 *all_errors* was added.
577
578 .. seealso::
579
580 The :func:`open_connection` function is a high-level alternative
581 API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`)
582 that can be used directly in async/await code.
583
584 .. method:: loop.create_datagram_endpoint(protocol_factory, \
585 local_addr=None, remote_addr=None, *, \
586 family=0, proto=0, flags=0, \
587 reuse_port=None, \
588 allow_broadcast=None, sock=None)
589 :async:
590
591 Create a datagram connection.
592
593 The socket family can be either :py:const:`~socket.AF_INET`,
594 :py:const:`~socket.AF_INET6`, or :py:const:`~socket.AF_UNIX`,
595 depending on *host* (or the *family* argument, if provided).
596
597 The socket type will be :py:const:`~socket.SOCK_DGRAM`.
598
599 *protocol_factory* must be a callable returning a
600 :ref:`protocol <asyncio-protocol>` implementation.
601
602 A tuple of ``(transport, protocol)`` is returned on success.
603
604 Other arguments:
605
606 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
607 to bind the socket locally. The *local_host* and *local_port*
608 are looked up using :meth:`getaddrinfo`.
609
610 .. note::
611
612 On Windows, when using the proactor event loop with ``local_addr=None``,
613 an :exc:`OSError` with :attr:`!errno.WSAEINVAL` will be raised
614 when running it.
615
616 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
617 to connect the socket to a remote address. The *remote_host* and
618 *remote_port* are looked up using :meth:`getaddrinfo`.
619
620 * *family*, *proto*, *flags* are the optional address family, protocol
621 and flags to be passed through to :meth:`getaddrinfo` for *host*
622 resolution. If given, these should all be integers from the
623 corresponding :mod:`socket` module constants.
624
625 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
626 same port as other existing endpoints are bound to, so long as they all
627 set this flag when being created. This option is not supported on Windows
628 and some Unixes. If the :ref:`socket.SO_REUSEPORT <socket-unix-constants>` constant is not
629 defined then this capability is unsupported.
630
631 * *allow_broadcast* tells the kernel to allow this endpoint to send
632 messages to the broadcast address.
633
634 * *sock* can optionally be specified in order to use a preexisting,
635 already connected, :class:`socket.socket` object to be used by the
636 transport. If specified, *local_addr* and *remote_addr* should be omitted
637 (must be :const:`None`).
638
639 .. note::
640
641 The *sock* argument transfers ownership of the socket to the
642 transport created. To close the socket, call the transport's
643 :meth:`~asyncio.BaseTransport.close` method.
644
645 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
646 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
647
648 .. versionchanged:: 3.4.4
649 The *family*, *proto*, *flags*, *reuse_address*, *reuse_port*,
650 *allow_broadcast*, and *sock* parameters were added.
651
652 .. versionchanged:: 3.8
653 Added support for Windows.
654
655 .. versionchanged:: 3.8.1
656 The *reuse_address* parameter is no longer supported, as using
657 :ref:`socket.SO_REUSEADDR <socket-unix-constants>`
658 poses a significant security concern for
659 UDP. Explicitly passing ``reuse_address=True`` will raise an exception.
660
661 When multiple processes with differing UIDs assign sockets to an
662 identical UDP socket address with ``SO_REUSEADDR``, incoming packets can
663 become randomly distributed among the sockets.
664
665 For supported platforms, *reuse_port* can be used as a replacement for
666 similar functionality. With *reuse_port*,
667 :ref:`socket.SO_REUSEPORT <socket-unix-constants>`
668 is used instead, which specifically
669 prevents processes with differing UIDs from assigning sockets to the same
670 socket address.
671
672 .. versionchanged:: 3.11
673 The *reuse_address* parameter, disabled since Python 3.8.1,
674 3.7.6 and 3.6.10, has been entirely removed.
675
676 .. method:: loop.create_unix_connection(protocol_factory, \
677 path=None, *, ssl=None, sock=None, \
678 server_hostname=None, ssl_handshake_timeout=None, \
679 ssl_shutdown_timeout=None)
680 :async:
681
682 Create a Unix connection.
683
684 The socket family will be :py:const:`~socket.AF_UNIX`; socket
685 type will be :py:const:`~socket.SOCK_STREAM`.
686
687 A tuple of ``(transport, protocol)`` is returned on success.
688
689 *path* is the name of a Unix domain socket and is required,
690 unless a *sock* parameter is specified. Abstract Unix sockets,
691 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are
692 supported.
693
694 See the documentation of the :meth:`loop.create_connection` method
695 for information about arguments to this method.
696
697 .. availability:: Unix.
698
699 .. versionchanged:: 3.7
700 Added the *ssl_handshake_timeout* parameter.
701 The *path* parameter can now be a :term:`path-like object`.
702
703 .. versionchanged:: 3.11
704
705 Added the *ssl_shutdown_timeout* parameter.
706
707
708 Creating network servers
709 ^^^^^^^^^^^^^^^^^^^^^^^^
710
711 .. _loop_create_server:
712
713 .. method:: loop.create_server(protocol_factory, \
714 host=None, port=None, *, \
715 family=socket.AF_UNSPEC, \
716 flags=socket.AI_PASSIVE, \
717 sock=None, backlog=100, ssl=None, \
718 reuse_address=None, reuse_port=None, \
719 keep_alive=None, \
720 ssl_handshake_timeout=None, \
721 ssl_shutdown_timeout=None, \
722 start_serving=True)
723 :async:
724
725 Create a TCP server (socket type :const:`~socket.SOCK_STREAM`) listening
726 on *port* of the *host* address.
727
728 Returns a :class:`Server` object.
729
730 Arguments:
731
732 * *protocol_factory* must be a callable returning a
733 :ref:`protocol <asyncio-protocol>` implementation.
734
735 * The *host* parameter can be set to several types which determine where
736 the server would be listening:
737
738 - If *host* is a string, the TCP server is bound to a single network
739 interface specified by *host*.
740
741 - If *host* is a sequence of strings, the TCP server is bound to all
742 network interfaces specified by the sequence.
743
744 - If *host* is an empty string or ``None``, all interfaces are
745 assumed and a list of multiple sockets will be returned (most likely
746 one for IPv4 and another one for IPv6).
747
748 * The *port* parameter can be set to specify which port the server should
749 listen on. If ``0`` or ``None`` (the default), a random unused port will
750 be selected (note that if *host* resolves to multiple network interfaces,
751 a different random port will be selected for each interface).
752
753 * *family* can be set to either :const:`socket.AF_INET` or
754 :const:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
755 If not set, the *family* will be determined from host name
756 (defaults to :const:`~socket.AF_UNSPEC`).
757
758 * *flags* is a bitmask for :meth:`getaddrinfo`.
759
760 * *sock* can optionally be specified in order to use a preexisting
761 socket object. If specified, *host* and *port* must not be specified.
762
763 .. note::
764
765 The *sock* argument transfers ownership of the socket to the
766 server created. To close the socket, call the server's
767 :meth:`~asyncio.Server.close` method.
768
769 * *backlog* is the maximum number of queued connections passed to
770 :meth:`~socket.socket.listen` (defaults to 100).
771
772 * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable
773 TLS over the accepted connections.
774
775 * *reuse_address* tells the kernel to reuse a local socket in
776 ``TIME_WAIT`` state, without waiting for its natural timeout to
777 expire. If not specified will automatically be set to ``True`` on
778 Unix.
779
780 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
781 same port as other existing endpoints are bound to, so long as they all
782 set this flag when being created. This option is not supported on
783 Windows.
784
785 * *keep_alive* set to ``True`` keeps connections active by enabling the
786 periodic transmission of messages.
787
788 .. versionchanged:: 3.13
789
790 Added the *keep_alive* parameter.
791
792 * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait
793 for the TLS handshake to complete before aborting the connection.
794 ``60.0`` seconds if ``None`` (default).
795
796 * *ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown
797 to complete before aborting the connection. ``30.0`` seconds if ``None``
798 (default).
799
800 * *start_serving* set to ``True`` (the default) causes the created server
801 to start accepting connections immediately. When set to ``False``,
802 the user should await on :meth:`Server.start_serving` or
803 :meth:`Server.serve_forever` to make the server to start accepting
804 connections.
805
806 .. versionchanged:: 3.5
807
808 Added support for SSL/TLS in :class:`ProactorEventLoop`.
809
810 .. versionchanged:: 3.5.1
811
812 The *host* parameter can be a sequence of strings.
813
814 .. versionchanged:: 3.6
815
816 Added *ssl_handshake_timeout* and *start_serving* parameters.
817 The socket option :ref:`socket.TCP_NODELAY <socket-unix-constants>` is set by default
818 for all TCP connections.
819
820 .. versionchanged:: 3.11
821
822 Added the *ssl_shutdown_timeout* parameter.
823
824 .. seealso::
825
826 The :func:`start_server` function is a higher-level alternative API
827 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
828 that can be used in an async/await code.
829
830
831 .. method:: loop.create_unix_server(protocol_factory, path=None, \
832 *, sock=None, backlog=100, ssl=None, \
833 ssl_handshake_timeout=None, \
834 ssl_shutdown_timeout=None, \
835 start_serving=True, cleanup_socket=True)
836 :async:
837
838 Similar to :meth:`loop.create_server` but works with the
839 :py:const:`~socket.AF_UNIX` socket family.
840
841 *path* is the name of a Unix domain socket, and is required,
842 unless a *sock* argument is provided. Abstract Unix sockets,
843 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
844 are supported.
845
846 If *cleanup_socket* is true then the Unix socket will automatically
847 be removed from the filesystem when the server is closed, unless the
848 socket has been replaced after the server has been created.
849
850 See the documentation of the :meth:`loop.create_server` method
851 for information about arguments to this method.
852
853 .. availability:: Unix.
854
855 .. versionchanged:: 3.7
856
857 Added the *ssl_handshake_timeout* and *start_serving* parameters.
858 The *path* parameter can now be a :class:`~pathlib.Path` object.
859
860 .. versionchanged:: 3.11
861
862 Added the *ssl_shutdown_timeout* parameter.
863
864 .. versionchanged:: 3.13
865
866 Added the *cleanup_socket* parameter.
867
868
869 .. method:: loop.connect_accepted_socket(protocol_factory, \
870 sock, *, ssl=None, ssl_handshake_timeout=None, \
871 ssl_shutdown_timeout=None)
872 :async:
873
874 Wrap an already accepted connection into a transport/protocol pair.
875
876 This method can be used by servers that accept connections outside
877 of asyncio but that use asyncio to handle them.
878
879 Parameters:
880
881 * *protocol_factory* must be a callable returning a
882 :ref:`protocol <asyncio-protocol>` implementation.
883
884 * *sock* is a preexisting socket object returned from
885 :meth:`socket.accept <socket.socket.accept>`.
886
887 .. note::
888
889 The *sock* argument transfers ownership of the socket to the
890 transport created. To close the socket, call the transport's
891 :meth:`~asyncio.BaseTransport.close` method.
892
893 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
894 the accepted connections.
895
896 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
897 wait for the SSL handshake to complete before aborting the connection.
898 ``60.0`` seconds if ``None`` (default).
899
900 * *ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown
901 to complete before aborting the connection. ``30.0`` seconds if ``None``
902 (default).
903
904 Returns a ``(transport, protocol)`` pair.
905
906 .. versionadded:: 3.5.3
907
908 .. versionchanged:: 3.7
909
910 Added the *ssl_handshake_timeout* parameter.
911
912 .. versionchanged:: 3.11
913
914 Added the *ssl_shutdown_timeout* parameter.
915
916
917 Transferring files
918 ^^^^^^^^^^^^^^^^^^
919
920 .. method:: loop.sendfile(transport, file, \
921 offset=0, count=None, *, fallback=True)
922 :async:
923
924 Send a *file* over a *transport*. Return the total number of bytes
925 sent.
926
927 The method uses high-performance :meth:`os.sendfile` if available.
928
929 *file* must be a regular file object opened in binary mode.
930
931 *offset* tells from where to start reading the file. If specified,
932 *count* is the total number of bytes to transmit as opposed to
933 sending the file until EOF is reached. File position is always updated,
934 even when this method raises an error, and
935 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
936 number of bytes sent.
937
938 *fallback* set to ``True`` makes asyncio to manually read and send
939 the file when the platform does not support the sendfile system call
940 (e.g. Windows or SSL socket on Unix).
941
942 Raise :exc:`SendfileNotAvailableError` if the system does not support
943 the *sendfile* syscall and *fallback* is ``False``.
944
945 .. versionadded:: 3.7
946
947
948 TLS Upgrade
949 ^^^^^^^^^^^
950
951 .. method:: loop.start_tls(transport, protocol, \
952 sslcontext, *, server_side=False, \
953 server_hostname=None, ssl_handshake_timeout=None, \
954 ssl_shutdown_timeout=None)
955 :async:
956
957 Upgrade an existing transport-based connection to TLS.
958
959 Create a TLS coder/decoder instance and insert it between the *transport*
960 and the *protocol*. The coder/decoder implements both *transport*-facing
961 protocol and *protocol*-facing transport.
962
963 Return the created two-interface instance. After *await*, the *protocol*
964 must stop using the original *transport* and communicate with the returned
965 object only because the coder caches *protocol*-side data and sporadically
966 exchanges extra TLS session packets with *transport*.
967
968 In some situations (e.g. when the passed transport is already closing) this
969 may return ``None``.
970
971 Parameters:
972
973 * *transport* and *protocol* instances that methods like
974 :meth:`~loop.create_server` and
975 :meth:`~loop.create_connection` return.
976
977 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
978
979 * *server_side* pass ``True`` when a server-side connection is being
980 upgraded (like the one created by :meth:`~loop.create_server`).
981
982 * *server_hostname*: sets or overrides the host name that the target
983 server's certificate will be matched against.
984
985 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to
986 wait for the TLS handshake to complete before aborting the connection.
987 ``60.0`` seconds if ``None`` (default).
988
989 * *ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown
990 to complete before aborting the connection. ``30.0`` seconds if ``None``
991 (default).
992
993 .. versionadded:: 3.7
994
995 .. versionchanged:: 3.11
996
997 Added the *ssl_shutdown_timeout* parameter.
998
999
1000
1001 Watching file descriptors
1002 ^^^^^^^^^^^^^^^^^^^^^^^^^
1003
1004 .. method:: loop.add_reader(fd, callback, *args)
1005
1006 Start monitoring the *fd* file descriptor for read availability and
1007 invoke *callback* with the specified arguments once *fd* is available for
1008 reading.
1009
1010 Any preexisting callback registered for *fd* is cancelled and replaced by
1011 *callback*.
1012
1013 .. method:: loop.remove_reader(fd)
1014
1015 Stop monitoring the *fd* file descriptor for read availability. Returns
1016 ``True`` if *fd* was previously being monitored for reads.
1017
1018 .. method:: loop.add_writer(fd, callback, *args)
1019
1020 Start monitoring the *fd* file descriptor for write availability and
1021 invoke *callback* with the specified arguments once *fd* is available for
1022 writing.
1023
1024 Any preexisting callback registered for *fd* is cancelled and replaced by
1025 *callback*.
1026
1027 Use :func:`functools.partial` :ref:`to pass keyword arguments
1028 <asyncio-pass-keywords>` to *callback*.
1029
1030 .. method:: loop.remove_writer(fd)
1031
1032 Stop monitoring the *fd* file descriptor for write availability. Returns
1033 ``True`` if *fd* was previously being monitored for writes.
1034
1035 See also :ref:`Platform Support <asyncio-platform-support>` section
1036 for some limitations of these methods.
1037
1038
1039 Working with socket objects directly
1040 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1041
1042 In general, protocol implementations that use transport-based APIs
1043 such as :meth:`loop.create_connection` and :meth:`loop.create_server`
1044 are faster than implementations that work with sockets directly.
1045 However, there are some use cases when performance is not critical, and
1046 working with :class:`~socket.socket` objects directly is more
1047 convenient.
1048
1049 .. method:: loop.sock_recv(sock, nbytes)
1050 :async:
1051
1052 Receive up to *nbytes* from *sock*. Asynchronous version of
1053 :meth:`socket.recv() <socket.socket.recv>`.
1054
1055 Return the received data as a bytes object.
1056
1057 *sock* must be a non-blocking socket.
1058
1059 .. versionchanged:: 3.7
1060 Even though this method was always documented as a coroutine
1061 method, releases before Python 3.7 returned a :class:`Future`.
1062 Since Python 3.7 this is an ``async def`` method.
1063
1064 .. method:: loop.sock_recv_into(sock, buf)
1065 :async:
1066
1067 Receive data from *sock* into the *buf* buffer. Modeled after the blocking
1068 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
1069
1070 Return the number of bytes written to the buffer.
1071
1072 *sock* must be a non-blocking socket.
1073
1074 .. versionadded:: 3.7
1075
1076 .. method:: loop.sock_recvfrom(sock, bufsize)
1077 :async:
1078
1079 Receive a datagram of up to *bufsize* from *sock*. Asynchronous version of
1080 :meth:`socket.recvfrom() <socket.socket.recvfrom>`.
1081
1082 Return a tuple of (received data, remote address).
1083
1084 *sock* must be a non-blocking socket.
1085
1086 .. versionadded:: 3.11
1087
1088 .. method:: loop.sock_recvfrom_into(sock, buf, nbytes=0)
1089 :async:
1090
1091 Receive a datagram of up to *nbytes* from *sock* into *buf*.
1092 Asynchronous version of
1093 :meth:`socket.recvfrom_into() <socket.socket.recvfrom_into>`.
1094
1095 Return a tuple of (number of bytes received, remote address).
1096
1097 *sock* must be a non-blocking socket.
1098
1099 .. versionadded:: 3.11
1100
1101 .. method:: loop.sock_sendall(sock, data)
1102 :async:
1103
1104 Send *data* to the *sock* socket. Asynchronous version of
1105 :meth:`socket.sendall() <socket.socket.sendall>`.
1106
1107 This method continues to send to the socket until either all data
1108 in *data* has been sent or an error occurs. ``None`` is returned
1109 on success. On error, an exception is raised. Additionally, there is no way
1110 to determine how much data, if any, was successfully processed by the
1111 receiving end of the connection.
1112
1113 *sock* must be a non-blocking socket.
1114
1115 .. versionchanged:: 3.7
1116 Even though the method was always documented as a coroutine
1117 method, before Python 3.7 it returned a :class:`Future`.
1118 Since Python 3.7, this is an ``async def`` method.
1119
1120 .. method:: loop.sock_sendto(sock, data, address)
1121 :async:
1122
1123 Send a datagram from *sock* to *address*.
1124 Asynchronous version of
1125 :meth:`socket.sendto() <socket.socket.sendto>`.
1126
1127 Return the number of bytes sent.
1128
1129 *sock* must be a non-blocking socket.
1130
1131 .. versionadded:: 3.11
1132
1133 .. method:: loop.sock_connect(sock, address)
1134 :async:
1135
1136 Connect *sock* to a remote socket at *address*.
1137
1138 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
1139
1140 *sock* must be a non-blocking socket.
1141
1142 .. versionchanged:: 3.5.2
1143 ``address`` no longer needs to be resolved. ``sock_connect``
1144 will try to check if the *address* is already resolved by calling
1145 :func:`socket.inet_pton`. If not,
1146 :meth:`loop.getaddrinfo` will be used to resolve the
1147 *address*.
1148
1149 .. seealso::
1150
1151 :meth:`loop.create_connection`
1152 and :func:`asyncio.open_connection() <open_connection>`.
1153
1154
1155 .. method:: loop.sock_accept(sock)
1156 :async:
1157
1158 Accept a connection. Modeled after the blocking
1159 :meth:`socket.accept() <socket.socket.accept>` method.
1160
1161 The socket must be bound to an address and listening
1162 for connections. The return value is a pair ``(conn, address)`` where *conn*
1163 is a *new* socket object usable to send and receive data on the connection,
1164 and *address* is the address bound to the socket on the other end of the
1165 connection.
1166
1167 *sock* must be a non-blocking socket.
1168
1169 .. versionchanged:: 3.7
1170 Even though the method was always documented as a coroutine
1171 method, before Python 3.7 it returned a :class:`Future`.
1172 Since Python 3.7, this is an ``async def`` method.
1173
1174 .. seealso::
1175
1176 :meth:`loop.create_server` and :func:`start_server`.
1177
1178 .. method:: loop.sock_sendfile(sock, file, offset=0, count=None, \
1179 *, fallback=True)
1180 :async:
1181
1182 Send a file using high-performance :mod:`os.sendfile` if possible.
1183 Return the total number of bytes sent.
1184
1185 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
1186
1187 *sock* must be a non-blocking :const:`socket.SOCK_STREAM`
1188 :class:`~socket.socket`.
1189
1190 *file* must be a regular file object open in binary mode.
1191
1192 *offset* tells from where to start reading the file. If specified,
1193 *count* is the total number of bytes to transmit as opposed to
1194 sending the file until EOF is reached. File position is always updated,
1195 even when this method raises an error, and
1196 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
1197 number of bytes sent.
1198
1199 *fallback*, when set to ``True``, makes asyncio manually read and send
1200 the file when the platform does not support the sendfile syscall
1201 (e.g. Windows or SSL socket on Unix).
1202
1203 Raise :exc:`SendfileNotAvailableError` if the system does not support
1204 *sendfile* syscall and *fallback* is ``False``.
1205
1206 *sock* must be a non-blocking socket.
1207
1208 .. versionadded:: 3.7
1209
1210
1211 DNS
1212 ^^^
1213
1214 .. method:: loop.getaddrinfo(host, port, *, family=0, \
1215 type=0, proto=0, flags=0)
1216 :async:
1217
1218 Asynchronous version of :meth:`socket.getaddrinfo`.
1219
1220 .. method:: loop.getnameinfo(sockaddr, flags=0)
1221 :async:
1222
1223 Asynchronous version of :meth:`socket.getnameinfo`.
1224
1225 .. note::
1226 Both *getaddrinfo* and *getnameinfo* internally utilize their synchronous
1227 versions through the loop's default thread pool executor.
1228 When this executor is saturated, these methods may experience delays,
1229 which higher-level networking libraries may report as increased timeouts.
1230 To mitigate this, consider using a custom executor for other user tasks,
1231 or setting a default executor with a larger number of workers.
1232
1233 .. versionchanged:: 3.7
1234 Both *getaddrinfo* and *getnameinfo* methods were always documented
1235 to return a coroutine, but prior to Python 3.7 they were, in fact,
1236 returning :class:`asyncio.Future` objects. Starting with Python 3.7
1237 both methods are coroutines.
1238
1239
1240 Working with pipes
1241 ^^^^^^^^^^^^^^^^^^
1242
1243 .. method:: loop.connect_read_pipe(protocol_factory, pipe)
1244 :async:
1245
1246 Register the read end of *pipe* in the event loop.
1247
1248 *protocol_factory* must be a callable returning an
1249 :ref:`asyncio protocol <asyncio-protocol>` implementation.
1250
1251 *pipe* is a :term:`file-like object <file object>`.
1252
1253 Return pair ``(transport, protocol)``, where *transport* supports
1254 the :class:`ReadTransport` interface and *protocol* is an object
1255 instantiated by the *protocol_factory*.
1256
1257 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
1258 non-blocking mode.
1259
1260 .. method:: loop.connect_write_pipe(protocol_factory, pipe)
1261 :async:
1262
1263 Register the write end of *pipe* in the event loop.
1264
1265 *protocol_factory* must be a callable returning an
1266 :ref:`asyncio protocol <asyncio-protocol>` implementation.
1267
1268 *pipe* is :term:`file-like object <file object>`.
1269
1270 Return pair ``(transport, protocol)``, where *transport* supports
1271 :class:`WriteTransport` interface and *protocol* is an object
1272 instantiated by the *protocol_factory*.
1273
1274 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
1275 non-blocking mode.
1276
1277 .. note::
1278
1279 :class:`SelectorEventLoop` does not support the above methods on
1280 Windows. Use :class:`ProactorEventLoop` instead for Windows.
1281
1282 .. seealso::
1283
1284 The :meth:`loop.subprocess_exec` and
1285 :meth:`loop.subprocess_shell` methods.
1286
1287
1288 Unix signals
1289 ^^^^^^^^^^^^
1290
1291 .. _loop_add_signal_handler:
1292
1293 .. method:: loop.add_signal_handler(signum, callback, *args)
1294
1295 Set *callback* as the handler for the *signum* signal.
1296
1297 The callback will be invoked by *loop*, along with other queued callbacks
1298 and runnable coroutines of that event loop. Unlike signal handlers
1299 registered using :func:`signal.signal`, a callback registered with this
1300 function is allowed to interact with the event loop.
1301
1302 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
1303 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
1304
1305 Use :func:`functools.partial` :ref:`to pass keyword arguments
1306 <asyncio-pass-keywords>` to *callback*.
1307
1308 Like :func:`signal.signal`, this function must be invoked in the main
1309 thread.
1310
1311 .. method:: loop.remove_signal_handler(sig)
1312
1313 Remove the handler for the *sig* signal.
1314
1315 Return ``True`` if the signal handler was removed, or ``False`` if
1316 no handler was set for the given signal.
1317
1318 .. availability:: Unix.
1319
1320 .. seealso::
1321
1322 The :mod:`signal` module.
1323
1324
1325 Executing code in thread or process pools
1326 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1327
1328 .. awaitablemethod:: loop.run_in_executor(executor, func, *args)
1329
1330 Arrange for *func* to be called in the specified executor.
1331
1332 The *executor* argument should be an :class:`concurrent.futures.Executor`
1333 instance. The default executor is used if *executor* is ``None``.
1334 The default executor can be set by :meth:`loop.set_default_executor`,
1335 otherwise, a :class:`concurrent.futures.ThreadPoolExecutor` will be
1336 lazy-initialized and used by :func:`run_in_executor` if needed.
1337
1338 Example::
1339
1340 import asyncio
1341 import concurrent.futures
1342
1343 def blocking_io():
1344 # File operations (such as logging) can block the
1345 # event loop: run them in a thread pool.
1346 with open('/dev/urandom', 'rb') as f:
1347 return f.read(100)
1348
1349 def cpu_bound():
1350 # CPU-bound operations will block the event loop:
1351 # in general it is preferable to run them in a
1352 # process pool.
1353 return sum(i * i for i in range(10 ** 7))
1354
1355 async def main():
1356 loop = asyncio.get_running_loop()
1357
1358 ## Options:
1359
1360 # 1. Run in the default loop's executor:
1361 result = await loop.run_in_executor(
1362 None, blocking_io)
1363 print('default thread pool', result)
1364
1365 # 2. Run in a custom thread pool:
1366 with concurrent.futures.ThreadPoolExecutor() as pool:
1367 result = await loop.run_in_executor(
1368 pool, blocking_io)
1369 print('custom thread pool', result)
1370
1371 # 3. Run in a custom process pool:
1372 with concurrent.futures.ProcessPoolExecutor() as pool:
1373 result = await loop.run_in_executor(
1374 pool, cpu_bound)
1375 print('custom process pool', result)
1376
1377 if __name__ == '__main__':
1378 asyncio.run(main())
1379
1380 Note that the entry point guard (``if __name__ == '__main__'``)
1381 is required for option 3 due to the peculiarities of :mod:`multiprocessing`,
1382 which is used by :class:`~concurrent.futures.ProcessPoolExecutor`.
1383 See :ref:`Safe importing of main module <multiprocessing-safe-main-import>`.
1384
1385 This method returns a :class:`asyncio.Future` object.
1386
1387 Use :func:`functools.partial` :ref:`to pass keyword arguments
1388 <asyncio-pass-keywords>` to *func*.
1389
1390 .. versionchanged:: 3.5.3
1391 :meth:`loop.run_in_executor` no longer configures the
1392 ``max_workers`` of the thread pool executor it creates, instead
1393 leaving it up to the thread pool executor
1394 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
1395 default.
1396
1397 .. method:: loop.set_default_executor(executor)
1398
1399 Set *executor* as the default executor used by :meth:`run_in_executor`.
1400 *executor* must be an instance of
1401 :class:`~concurrent.futures.ThreadPoolExecutor`.
1402
1403 .. versionchanged:: 3.11
1404 *executor* must be an instance of
1405 :class:`~concurrent.futures.ThreadPoolExecutor`.
1406
1407
1408 Error Handling API
1409 ^^^^^^^^^^^^^^^^^^
1410
1411 Allows customizing how exceptions are handled in the event loop.
1412
1413 .. method:: loop.set_exception_handler(handler)
1414
1415 Set *handler* as the new event loop exception handler.
1416
1417 If *handler* is ``None``, the default exception handler will
1418 be set. Otherwise, *handler* must be a callable with the signature
1419 matching ``(loop, context)``, where ``loop``
1420 is a reference to the active event loop, and ``context``
1421 is a ``dict`` object containing the details of the exception
1422 (see :meth:`call_exception_handler` documentation for details
1423 about context).
1424
1425 If the handler is called on behalf of a :class:`~asyncio.Task` or
1426 :class:`~asyncio.Handle`, it is run in the
1427 :class:`contextvars.Context` of that task or callback handle.
1428
1429 .. versionchanged:: 3.12
1430
1431 The handler may be called in the :class:`~contextvars.Context`
1432 of the task or handle where the exception originated.
1433
1434 .. method:: loop.get_exception_handler()
1435
1436 Return the current exception handler, or ``None`` if no custom
1437 exception handler was set.
1438
1439 .. versionadded:: 3.5.2
1440
1441 .. method:: loop.default_exception_handler(context)
1442
1443 Default exception handler.
1444
1445 This is called when an exception occurs and no exception
1446 handler is set. This can be called by a custom exception
1447 handler that wants to defer to the default handler behavior.
1448
1449 *context* parameter has the same meaning as in
1450 :meth:`call_exception_handler`.
1451
1452 .. method:: loop.call_exception_handler(context)
1453
1454 Call the current event loop exception handler.
1455
1456 *context* is a ``dict`` object containing the following keys
1457 (new keys may be introduced in future Python versions):
1458
1459 * 'message': Error message;
1460 * 'exception' (optional): Exception object;
1461 * 'future' (optional): :class:`asyncio.Future` instance;
1462 * 'task' (optional): :class:`asyncio.Task` instance;
1463 * 'handle' (optional): :class:`asyncio.Handle` instance;
1464 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1465 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1466 * 'socket' (optional): :class:`socket.socket` instance;
1467 * 'source_traceback' (optional): Traceback of the source;
1468 * 'handle_traceback' (optional): Traceback of the handle;
1469 * 'asyncgen' (optional): Asynchronous generator that caused
1470 the exception.
1471
1472 .. note::
1473
1474 This method should not be overloaded in subclassed
1475 event loops. For custom exception handling, use
1476 the :meth:`set_exception_handler` method.
1477
1478 Enabling debug mode
1479 ^^^^^^^^^^^^^^^^^^^
1480
1481 .. method:: loop.get_debug()
1482
1483 Get the debug mode (:class:`bool`) of the event loop.
1484
1485 The default value is ``True`` if the environment variable
1486 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1487 otherwise.
1488
1489 .. method:: loop.set_debug(enabled: bool)
1490
1491 Set the debug mode of the event loop.
1492
1493 .. versionchanged:: 3.7
1494
1495 The new :ref:`Python Development Mode <devmode>` can now also be used
1496 to enable the debug mode.
1497
1498 .. attribute:: loop.slow_callback_duration
1499
1500 This attribute can be used to set the
1501 minimum execution duration in seconds that is considered "slow".
1502 When debug mode is enabled, "slow" callbacks are logged.
1503
1504 Default value is 100 milliseconds.
1505
1506 .. seealso::
1507
1508 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
1509
1510
1511 Running Subprocesses
1512 ^^^^^^^^^^^^^^^^^^^^
1513
1514 Methods described in this subsections are low-level. In regular
1515 async/await code consider using the high-level
1516 :func:`asyncio.create_subprocess_shell` and
1517 :func:`asyncio.create_subprocess_exec` convenience functions instead.
1518
1519 .. note::
1520
1521 On Windows, the default event loop :class:`ProactorEventLoop` supports
1522 subprocesses, whereas :class:`SelectorEventLoop` does not. See
1523 :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>` for
1524 details.
1525
1526 .. _loop_subprocess_exec:
1527
1528 .. method:: loop.subprocess_exec(protocol_factory, *args, \
1529 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1530 stderr=subprocess.PIPE, **kwargs)
1531 :async:
1532
1533 Create a subprocess from one or more string arguments specified by
1534 *args*.
1535
1536 *args* must be a list of strings represented by:
1537
1538 * :class:`str`;
1539 * or :class:`bytes`, encoded to the
1540 :ref:`filesystem encoding <filesystem-encoding>`.
1541
1542 The first string specifies the program executable,
1543 and the remaining strings specify the arguments. Together, string
1544 arguments form the ``argv`` of the program.
1545
1546 This is similar to the standard library :class:`subprocess.Popen`
1547 class called with ``shell=False`` and the list of strings passed as
1548 the first argument; however, where :class:`~subprocess.Popen` takes
1549 a single argument which is list of strings, *subprocess_exec*
1550 takes multiple string arguments.
1551
1552 The *protocol_factory* must be a callable returning a subclass of the
1553 :class:`asyncio.SubprocessProtocol` class.
1554
1555 Other parameters:
1556
1557 * *stdin* can be any of these:
1558
1559 * a file-like object
1560 * an existing file descriptor (a positive integer), for example those created with :meth:`os.pipe`
1561 * the :const:`subprocess.PIPE` constant (default) which will create a new
1562 pipe and connect it,
1563 * the value ``None`` which will make the subprocess inherit the file
1564 descriptor from this process
1565 * the :const:`subprocess.DEVNULL` constant which indicates that the
1566 special :data:`os.devnull` file will be used
1567
1568 * *stdout* can be any of these:
1569
1570 * a file-like object
1571 * the :const:`subprocess.PIPE` constant (default) which will create a new
1572 pipe and connect it,
1573 * the value ``None`` which will make the subprocess inherit the file
1574 descriptor from this process
1575 * the :const:`subprocess.DEVNULL` constant which indicates that the
1576 special :data:`os.devnull` file will be used
1577
1578 * *stderr* can be any of these:
1579
1580 * a file-like object
1581 * the :const:`subprocess.PIPE` constant (default) which will create a new
1582 pipe and connect it,
1583 * the value ``None`` which will make the subprocess inherit the file
1584 descriptor from this process
1585 * the :const:`subprocess.DEVNULL` constant which indicates that the
1586 special :data:`os.devnull` file will be used
1587 * the :const:`subprocess.STDOUT` constant which will connect the standard
1588 error stream to the process' standard output stream
1589
1590 * All other keyword arguments are passed to :class:`subprocess.Popen`
1591 without interpretation, except for *bufsize*, *universal_newlines*,
1592 *shell*, *text*, *encoding* and *errors*, which should not be specified
1593 at all.
1594
1595 The ``asyncio`` subprocess API does not support decoding the streams
1596 as text. :func:`bytes.decode` can be used to convert the bytes returned
1597 from the stream to text.
1598
1599 If a file-like object passed as *stdin*, *stdout* or *stderr* represents a
1600 pipe, then the other side of this pipe should be registered with
1601 :meth:`~loop.connect_write_pipe` or :meth:`~loop.connect_read_pipe` for use
1602 with the event loop.
1603
1604 See the constructor of the :class:`subprocess.Popen` class
1605 for documentation on other arguments.
1606
1607 Returns a pair of ``(transport, protocol)``, where *transport*
1608 conforms to the :class:`asyncio.SubprocessTransport` base class and
1609 *protocol* is an object instantiated by the *protocol_factory*.
1610
1611 If the transport is closed or is garbage collected, the child process
1612 is killed if it is still running.
1613
1614 .. method:: loop.subprocess_shell(protocol_factory, cmd, *, \
1615 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1616 stderr=subprocess.PIPE, **kwargs)
1617 :async:
1618
1619 Create a subprocess from *cmd*, which can be a :class:`str` or a
1620 :class:`bytes` string encoded to the
1621 :ref:`filesystem encoding <filesystem-encoding>`,
1622 using the platform's "shell" syntax.
1623
1624 This is similar to the standard library :class:`subprocess.Popen`
1625 class called with ``shell=True``.
1626
1627 The *protocol_factory* must be a callable returning a subclass of the
1628 :class:`SubprocessProtocol` class.
1629
1630 See :meth:`~loop.subprocess_exec` for more details about
1631 the remaining arguments.
1632
1633 Returns a pair of ``(transport, protocol)``, where *transport*
1634 conforms to the :class:`SubprocessTransport` base class and
1635 *protocol* is an object instantiated by the *protocol_factory*.
1636
1637 If the transport is closed or is garbage collected, the child process
1638 is killed if it is still running.
1639
1640 .. note::
1641 It is the application's responsibility to ensure that all whitespace
1642 and special characters are quoted appropriately to avoid `shell injection
1643 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1644 vulnerabilities. The :func:`shlex.quote` function can be used to
1645 properly escape whitespace and special characters in strings that
1646 are going to be used to construct shell commands.
1647
1648
1649 Callback Handles
1650 ================
1651
1652 .. class:: Handle
1653
1654 A callback wrapper object returned by :meth:`loop.call_soon`,
1655 :meth:`loop.call_soon_threadsafe`.
1656
1657 .. method:: get_context()
1658
1659 Return the :class:`contextvars.Context` object
1660 associated with the handle.
1661
1662 .. versionadded:: 3.12
1663
1664 .. method:: cancel()
1665
1666 Cancel the callback. If the callback has already been canceled
1667 or executed, this method has no effect.
1668
1669 .. method:: cancelled()
1670
1671 Return ``True`` if the callback was cancelled.
1672
1673 .. versionadded:: 3.7
1674
1675 .. class:: TimerHandle
1676
1677 A callback wrapper object returned by :meth:`loop.call_later`,
1678 and :meth:`loop.call_at`.
1679
1680 This class is a subclass of :class:`Handle`.
1681
1682 .. method:: when()
1683
1684 Return a scheduled callback time as :class:`float` seconds.
1685
1686 The time is an absolute timestamp, using the same time
1687 reference as :meth:`loop.time`.
1688
1689 .. versionadded:: 3.7
1690
1691
1692 Server Objects
1693 ==============
1694
1695 Server objects are created by :meth:`loop.create_server`,
1696 :meth:`loop.create_unix_server`, :func:`start_server`,
1697 and :func:`start_unix_server` functions.
1698
1699 Do not instantiate the :class:`Server` class directly.
1700
1701 .. class:: Server
1702
1703 *Server* objects are asynchronous context managers. When used in an
1704 ``async with`` statement, it's guaranteed that the Server object is
1705 closed and not accepting new connections when the ``async with``
1706 statement is completed::
1707
1708 srv = await loop.create_server(...)
1709
1710 async with srv:
1711 # some code
1712
1713 # At this point, srv is closed and no longer accepts new connections.
1714
1715
1716 .. versionchanged:: 3.7
1717 Server object is an asynchronous context manager since Python 3.7.
1718
1719 .. versionchanged:: 3.11
1720 This class was exposed publicly as ``asyncio.Server`` in Python 3.9.11, 3.10.3 and 3.11.
1721
1722 .. method:: close()
1723
1724 Stop serving: close listening sockets and set the :attr:`sockets`
1725 attribute to ``None``.
1726
1727 The sockets that represent existing incoming client connections
1728 are left open.
1729
1730 The server is closed asynchronously; use the :meth:`wait_closed`
1731 coroutine to wait until the server is closed (and no more
1732 connections are active).
1733
1734 .. method:: close_clients()
1735
1736 Close all existing incoming client connections.
1737
1738 Calls :meth:`~asyncio.BaseTransport.close` on all associated
1739 transports.
1740
1741 :meth:`close` should be called before :meth:`close_clients` when
1742 closing the server to avoid races with new clients connecting.
1743
1744 .. versionadded:: 3.13
1745
1746 .. method:: abort_clients()
1747
1748 Close all existing incoming client connections immediately,
1749 without waiting for pending operations to complete.
1750
1751 Calls :meth:`~asyncio.WriteTransport.abort` on all associated
1752 transports.
1753
1754 :meth:`close` should be called before :meth:`abort_clients` when
1755 closing the server to avoid races with new clients connecting.
1756
1757 .. versionadded:: 3.13
1758
1759 .. method:: get_loop()
1760
1761 Return the event loop associated with the server object.
1762
1763 .. versionadded:: 3.7
1764
1765 .. method:: start_serving()
1766 :async:
1767
1768 Start accepting connections.
1769
1770 This method is idempotent, so it can be called when
1771 the server is already serving.
1772
1773 The *start_serving* keyword-only parameter to
1774 :meth:`loop.create_server` and
1775 :meth:`asyncio.start_server` allows creating a Server object
1776 that is not accepting connections initially. In this case
1777 ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used
1778 to make the Server start accepting connections.
1779
1780 .. versionadded:: 3.7
1781
1782 .. method:: serve_forever()
1783 :async:
1784
1785 Start accepting connections until the coroutine is cancelled.
1786 Cancellation of ``serve_forever`` task causes the server
1787 to be closed.
1788
1789 This method can be called if the server is already accepting
1790 connections. Only one ``serve_forever`` task can exist per
1791 one *Server* object.
1792
1793 Example::
1794
1795 async def client_connected(reader, writer):
1796 # Communicate with the client with
1797 # reader/writer streams. For example:
1798 await reader.readline()
1799
1800 async def main(host, port):
1801 srv = await asyncio.start_server(
1802 client_connected, host, port)
1803 await srv.serve_forever()
1804
1805 asyncio.run(main('127.0.0.1', 0))
1806
1807 .. versionadded:: 3.7
1808
1809 .. method:: is_serving()
1810
1811 Return ``True`` if the server is accepting new connections.
1812
1813 .. versionadded:: 3.7
1814
1815 .. method:: wait_closed()
1816 :async:
1817
1818 Wait until the :meth:`close` method completes and all active
1819 connections have finished.
1820
1821 .. attribute:: sockets
1822
1823 List of socket-like objects, ``asyncio.trsock.TransportSocket``, which
1824 the server is listening on.
1825
1826 .. versionchanged:: 3.7
1827 Prior to Python 3.7 ``Server.sockets`` used to return an
1828 internal list of server sockets directly. In 3.7 a copy
1829 of that list is returned.
1830
1831
1832 .. _asyncio-event-loops:
1833 .. _asyncio-event-loop-implementations:
1834
1835 Event Loop Implementations
1836 ==========================
1837
1838 asyncio ships with two different event loop implementations:
1839 :class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
1840
1841 By default asyncio is configured to use :class:`EventLoop`.
1842
1843
1844 .. class:: SelectorEventLoop
1845
1846 A subclass of :class:`AbstractEventLoop` based on the
1847 :mod:`selectors` module.
1848
1849 Uses the most efficient *selector* available for the given
1850 platform. It is also possible to manually configure the
1851 exact selector implementation to be used::
1852
1853 import asyncio
1854 import selectors
1855
1856 class MyPolicy(asyncio.DefaultEventLoopPolicy):
1857 def new_event_loop(self):
1858 selector = selectors.SelectSelector()
1859 return asyncio.SelectorEventLoop(selector)
1860
1861 asyncio.set_event_loop_policy(MyPolicy())
1862
1863
1864 .. availability:: Unix, Windows.
1865
1866
1867 .. class:: ProactorEventLoop
1868
1869 A subclass of :class:`AbstractEventLoop` for Windows that uses "I/O Completion Ports" (IOCP).
1870
1871 .. availability:: Windows.
1872
1873 .. seealso::
1874
1875 `MSDN documentation on I/O Completion Ports
1876 <https://learn.microsoft.com/windows/win32/fileio/i-o-completion-ports>`_.
1877
1878 .. class:: EventLoop
1879
1880 An alias to the most efficient available subclass of :class:`AbstractEventLoop` for the given
1881 platform.
1882
1883 It is an alias to :class:`SelectorEventLoop` on Unix and :class:`ProactorEventLoop` on Windows.
1884
1885 .. versionadded:: 3.13
1886
1887 .. class:: AbstractEventLoop
1888
1889 Abstract base class for asyncio-compliant event loops.
1890
1891 The :ref:`asyncio-event-loop-methods` section lists all
1892 methods that an alternative implementation of ``AbstractEventLoop``
1893 should have defined.
1894
1895
1896 Examples
1897 ========
1898
1899 Note that all examples in this section **purposefully** show how
1900 to use the low-level event loop APIs, such as :meth:`loop.run_forever`
1901 and :meth:`loop.call_soon`. Modern asyncio applications rarely
1902 need to be written this way; consider using the high-level functions
1903 like :func:`asyncio.run`.
1904
1905
1906 .. _asyncio_example_lowlevel_helloworld:
1907
1908 Hello World with call_soon()
1909 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1910
1911 An example using the :meth:`loop.call_soon` method to schedule a
1912 callback. The callback displays ``"Hello World"`` and then stops the
1913 event loop::
1914
1915 import asyncio
1916
1917 def hello_world(loop):
1918 """A callback to print 'Hello World' and stop the event loop"""
1919 print('Hello World')
1920 loop.stop()
1921
1922 loop = asyncio.new_event_loop()
1923
1924 # Schedule a call to hello_world()
1925 loop.call_soon(hello_world, loop)
1926
1927 # Blocking call interrupted by loop.stop()
1928 try:
1929 loop.run_forever()
1930 finally:
1931 loop.close()
1932
1933 .. seealso::
1934
1935 A similar :ref:`Hello World <coroutine>`
1936 example created with a coroutine and the :func:`run` function.
1937
1938
1939 .. _asyncio_example_call_later:
1940
1941 Display the current date with call_later()
1942 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1943
1944 An example of a callback displaying the current date every second. The
1945 callback uses the :meth:`loop.call_later` method to reschedule itself
1946 after 5 seconds, and then stops the event loop::
1947
1948 import asyncio
1949 import datetime
1950
1951 def display_date(end_time, loop):
1952 print(datetime.datetime.now())
1953 if (loop.time() + 1.0) < end_time:
1954 loop.call_later(1, display_date, end_time, loop)
1955 else:
1956 loop.stop()
1957
1958 loop = asyncio.new_event_loop()
1959
1960 # Schedule the first call to display_date()
1961 end_time = loop.time() + 5.0
1962 loop.call_soon(display_date, end_time, loop)
1963
1964 # Blocking call interrupted by loop.stop()
1965 try:
1966 loop.run_forever()
1967 finally:
1968 loop.close()
1969
1970 .. seealso::
1971
1972 A similar :ref:`current date <asyncio_example_sleep>` example
1973 created with a coroutine and the :func:`run` function.
1974
1975
1976 .. _asyncio_example_watch_fd:
1977
1978 Watch a file descriptor for read events
1979 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1980
1981 Wait until a file descriptor received some data using the
1982 :meth:`loop.add_reader` method and then close the event loop::
1983
1984 import asyncio
1985 from socket import socketpair
1986
1987 # Create a pair of connected file descriptors
1988 rsock, wsock = socketpair()
1989
1990 loop = asyncio.new_event_loop()
1991
1992 def reader():
1993 data = rsock.recv(100)
1994 print("Received:", data.decode())
1995
1996 # We are done: unregister the file descriptor
1997 loop.remove_reader(rsock)
1998
1999 # Stop the event loop
2000 loop.stop()
2001
2002 # Register the file descriptor for read event
2003 loop.add_reader(rsock, reader)
2004
2005 # Simulate the reception of data from the network
2006 loop.call_soon(wsock.send, 'abc'.encode())
2007
2008 try:
2009 # Run the event loop
2010 loop.run_forever()
2011 finally:
2012 # We are done. Close sockets and the event loop.
2013 rsock.close()
2014 wsock.close()
2015 loop.close()
2016
2017 .. seealso::
2018
2019 * A similar :ref:`example <asyncio_example_create_connection>`
2020 using transports, protocols, and the
2021 :meth:`loop.create_connection` method.
2022
2023 * Another similar :ref:`example <asyncio_example_create_connection-streams>`
2024 using the high-level :func:`asyncio.open_connection` function
2025 and streams.
2026
2027
2028 .. _asyncio_example_unix_signals:
2029
2030 Set signal handlers for SIGINT and SIGTERM
2031 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2032
2033 (This ``signals`` example only works on Unix.)
2034
2035 Register handlers for signals :const:`~signal.SIGINT` and :const:`~signal.SIGTERM`
2036 using the :meth:`loop.add_signal_handler` method::
2037
2038 import asyncio
2039 import functools
2040 import os
2041 import signal
2042
2043 def ask_exit(signame, loop):
2044 print("got signal %s: exit" % signame)
2045 loop.stop()
2046
2047 async def main():
2048 loop = asyncio.get_running_loop()
2049
2050 for signame in {'SIGINT', 'SIGTERM'}:
2051 loop.add_signal_handler(
2052 getattr(signal, signame),
2053 functools.partial(ask_exit, signame, loop))
2054
2055 await asyncio.sleep(3600)
2056
2057 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
2058 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
2059
2060 asyncio.run(main())