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