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