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