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 .. versionadded:: 3.8 460 461 Added the *happy_eyeballs_delay* and *interleave* parameters. 462 463 Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. 464 When a server's IPv4 path and protocol are working, but the server's 465 IPv6 path and protocol are not working, a dual-stack client 466 application experiences significant connection delay compared to an 467 IPv4-only client. This is undesirable because it causes the dual- 468 stack client to have a worse user experience. This document 469 specifies requirements for algorithms that reduce this user-visible 470 delay and provides an algorithm. 471 472 For more information: https://tools.ietf.org/html/rfc6555 473 474 .. versionadded:: 3.7 475 476 The *ssl_handshake_timeout* parameter. 477 478 .. versionchanged:: 3.6 479 480 The socket option :py:data:`~socket.TCP_NODELAY` is set by default 481 for all TCP connections. 482 483 .. versionchanged:: 3.5 484 485 Added support for SSL/TLS in :class:`ProactorEventLoop`. 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 .. versionadded:: 3.7 592 593 The *ssl_handshake_timeout* parameter. 594 595 .. versionchanged:: 3.7 596 597 The *path* parameter can now be a :term:`path-like object`. 598 599 600Creating network servers 601^^^^^^^^^^^^^^^^^^^^^^^^ 602 603.. coroutinemethod:: loop.create_server(protocol_factory, \ 604 host=None, port=None, *, \ 605 family=socket.AF_UNSPEC, \ 606 flags=socket.AI_PASSIVE, \ 607 sock=None, backlog=100, ssl=None, \ 608 reuse_address=None, reuse_port=None, \ 609 ssl_handshake_timeout=None, start_serving=True) 610 611 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening 612 on *port* of the *host* address. 613 614 Returns a :class:`Server` object. 615 616 Arguments: 617 618 * *protocol_factory* must be a callable returning a 619 :ref:`protocol <asyncio-protocol>` implementation. 620 621 * The *host* parameter can be set to several types which determine where 622 the server would be listening: 623 624 - If *host* is a string, the TCP server is bound to a single network 625 interface specified by *host*. 626 627 - If *host* is a sequence of strings, the TCP server is bound to all 628 network interfaces specified by the sequence. 629 630 - If *host* is an empty string or ``None``, all interfaces are 631 assumed and a list of multiple sockets will be returned (most likely 632 one for IPv4 and another one for IPv6). 633 634 * The *port* parameter can be set to specify which port the server should 635 listen on. If ``0`` or ``None`` (the default), a random unused port will 636 be selected (note that if *host* resolves to multiple network interfaces, 637 a different random port will be selected for each interface). 638 639 * *family* can be set to either :data:`socket.AF_INET` or 640 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. 641 If not set, the *family* will be determined from host name 642 (defaults to :data:`~socket.AF_UNSPEC`). 643 644 * *flags* is a bitmask for :meth:`getaddrinfo`. 645 646 * *sock* can optionally be specified in order to use a preexisting 647 socket object. If specified, *host* and *port* must not be specified. 648 649 * *backlog* is the maximum number of queued connections passed to 650 :meth:`~socket.socket.listen` (defaults to 100). 651 652 * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable 653 TLS over the accepted connections. 654 655 * *reuse_address* tells the kernel to reuse a local socket in 656 ``TIME_WAIT`` state, without waiting for its natural timeout to 657 expire. If not specified will automatically be set to ``True`` on 658 Unix. 659 660 * *reuse_port* tells the kernel to allow this endpoint to be bound to the 661 same port as other existing endpoints are bound to, so long as they all 662 set this flag when being created. This option is not supported on 663 Windows. 664 665 * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait 666 for the TLS handshake to complete before aborting the connection. 667 ``60.0`` seconds if ``None`` (default). 668 669 * *start_serving* set to ``True`` (the default) causes the created server 670 to start accepting connections immediately. When set to ``False``, 671 the user should await on :meth:`Server.start_serving` or 672 :meth:`Server.serve_forever` to make the server to start accepting 673 connections. 674 675 .. versionadded:: 3.7 676 677 Added *ssl_handshake_timeout* and *start_serving* parameters. 678 679 .. versionchanged:: 3.6 680 681 The socket option :py:data:`~socket.TCP_NODELAY` is set by default 682 for all TCP connections. 683 684 .. versionchanged:: 3.5 685 686 Added support for SSL/TLS in :class:`ProactorEventLoop`. 687 688 .. versionchanged:: 3.5.1 689 690 The *host* parameter can be a sequence of strings. 691 692 .. seealso:: 693 694 The :func:`start_server` function is a higher-level alternative API 695 that returns a pair of :class:`StreamReader` and :class:`StreamWriter` 696 that can be used in an async/await code. 697 698 699.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \ 700 *, sock=None, backlog=100, ssl=None, \ 701 ssl_handshake_timeout=None, start_serving=True) 702 703 Similar to :meth:`loop.create_server` but works with the 704 :py:data:`~socket.AF_UNIX` socket family. 705 706 *path* is the name of a Unix domain socket, and is required, 707 unless a *sock* argument is provided. Abstract Unix sockets, 708 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths 709 are supported. 710 711 See the documentation of the :meth:`loop.create_server` method 712 for information about arguments to this method. 713 714 .. availability:: Unix. 715 716 .. versionadded:: 3.7 717 718 The *ssl_handshake_timeout* and *start_serving* parameters. 719 720 .. versionchanged:: 3.7 721 722 The *path* parameter can now be a :class:`~pathlib.Path` object. 723 724.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \ 725 sock, *, ssl=None, ssl_handshake_timeout=None) 726 727 Wrap an already accepted connection into a transport/protocol pair. 728 729 This method can be used by servers that accept connections outside 730 of asyncio but that use asyncio to handle them. 731 732 Parameters: 733 734 * *protocol_factory* must be a callable returning a 735 :ref:`protocol <asyncio-protocol>` implementation. 736 737 * *sock* is a preexisting socket object returned from 738 :meth:`socket.accept <socket.socket.accept>`. 739 740 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over 741 the accepted connections. 742 743 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to 744 wait for the SSL handshake to complete before aborting the connection. 745 ``60.0`` seconds if ``None`` (default). 746 747 Returns a ``(transport, protocol)`` pair. 748 749 .. versionadded:: 3.7 750 751 The *ssl_handshake_timeout* parameter. 752 753 .. versionadded:: 3.5.3 754 755 756Transferring files 757^^^^^^^^^^^^^^^^^^ 758 759.. coroutinemethod:: loop.sendfile(transport, file, \ 760 offset=0, count=None, *, fallback=True) 761 762 Send a *file* over a *transport*. Return the total number of bytes 763 sent. 764 765 The method uses high-performance :meth:`os.sendfile` if available. 766 767 *file* must be a regular file object opened in binary mode. 768 769 *offset* tells from where to start reading the file. If specified, 770 *count* is the total number of bytes to transmit as opposed to 771 sending the file until EOF is reached. File position is always updated, 772 even when this method raises an error, and 773 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual 774 number of bytes sent. 775 776 *fallback* set to ``True`` makes asyncio to manually read and send 777 the file when the platform does not support the sendfile system call 778 (e.g. Windows or SSL socket on Unix). 779 780 Raise :exc:`SendfileNotAvailableError` if the system does not support 781 the *sendfile* syscall and *fallback* is ``False``. 782 783 .. versionadded:: 3.7 784 785 786TLS Upgrade 787^^^^^^^^^^^ 788 789.. coroutinemethod:: loop.start_tls(transport, protocol, \ 790 sslcontext, *, server_side=False, \ 791 server_hostname=None, ssl_handshake_timeout=None) 792 793 Upgrade an existing transport-based connection to TLS. 794 795 Return a new transport instance, that the *protocol* must start using 796 immediately after the *await*. The *transport* instance passed to 797 the *start_tls* method should never be used again. 798 799 Parameters: 800 801 * *transport* and *protocol* instances that methods like 802 :meth:`~loop.create_server` and 803 :meth:`~loop.create_connection` return. 804 805 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`. 806 807 * *server_side* pass ``True`` when a server-side connection is being 808 upgraded (like the one created by :meth:`~loop.create_server`). 809 810 * *server_hostname*: sets or overrides the host name that the target 811 server's certificate will be matched against. 812 813 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to 814 wait for the TLS handshake to complete before aborting the connection. 815 ``60.0`` seconds if ``None`` (default). 816 817 .. versionadded:: 3.7 818 819 820Watching file descriptors 821^^^^^^^^^^^^^^^^^^^^^^^^^ 822 823.. method:: loop.add_reader(fd, callback, *args) 824 825 Start monitoring the *fd* file descriptor for read availability and 826 invoke *callback* with the specified arguments once *fd* is available for 827 reading. 828 829.. method:: loop.remove_reader(fd) 830 831 Stop monitoring the *fd* file descriptor for read availability. 832 833.. method:: loop.add_writer(fd, callback, *args) 834 835 Start monitoring the *fd* file descriptor for write availability and 836 invoke *callback* with the specified arguments once *fd* is available for 837 writing. 838 839 Use :func:`functools.partial` :ref:`to pass keyword arguments 840 <asyncio-pass-keywords>` to *callback*. 841 842.. method:: loop.remove_writer(fd) 843 844 Stop monitoring the *fd* file descriptor for write availability. 845 846See also :ref:`Platform Support <asyncio-platform-support>` section 847for some limitations of these methods. 848 849 850Working with socket objects directly 851^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 852 853In general, protocol implementations that use transport-based APIs 854such as :meth:`loop.create_connection` and :meth:`loop.create_server` 855are faster than implementations that work with sockets directly. 856However, there are some use cases when performance is not critical, and 857working with :class:`~socket.socket` objects directly is more 858convenient. 859 860.. coroutinemethod:: loop.sock_recv(sock, nbytes) 861 862 Receive up to *nbytes* from *sock*. Asynchronous version of 863 :meth:`socket.recv() <socket.socket.recv>`. 864 865 Return the received data as a bytes object. 866 867 *sock* must be a non-blocking socket. 868 869 .. versionchanged:: 3.7 870 Even though this method was always documented as a coroutine 871 method, releases before Python 3.7 returned a :class:`Future`. 872 Since Python 3.7 this is an ``async def`` method. 873 874.. coroutinemethod:: loop.sock_recv_into(sock, buf) 875 876 Receive data from *sock* into the *buf* buffer. Modeled after the blocking 877 :meth:`socket.recv_into() <socket.socket.recv_into>` method. 878 879 Return the number of bytes written to the buffer. 880 881 *sock* must be a non-blocking socket. 882 883 .. versionadded:: 3.7 884 885.. coroutinemethod:: loop.sock_sendall(sock, data) 886 887 Send *data* to the *sock* socket. Asynchronous version of 888 :meth:`socket.sendall() <socket.socket.sendall>`. 889 890 This method continues to send to the socket until either all data 891 in *data* has been sent or an error occurs. ``None`` is returned 892 on success. On error, an exception is raised. Additionally, there is no way 893 to determine how much data, if any, was successfully processed by the 894 receiving end of the connection. 895 896 *sock* must be a non-blocking socket. 897 898 .. versionchanged:: 3.7 899 Even though the method was always documented as a coroutine 900 method, before Python 3.7 it returned an :class:`Future`. 901 Since Python 3.7, this is an ``async def`` method. 902 903.. coroutinemethod:: loop.sock_connect(sock, address) 904 905 Connect *sock* to a remote socket at *address*. 906 907 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`. 908 909 *sock* must be a non-blocking socket. 910 911 .. versionchanged:: 3.5.2 912 ``address`` no longer needs to be resolved. ``sock_connect`` 913 will try to check if the *address* is already resolved by calling 914 :func:`socket.inet_pton`. If not, 915 :meth:`loop.getaddrinfo` will be used to resolve the 916 *address*. 917 918 .. seealso:: 919 920 :meth:`loop.create_connection` 921 and :func:`asyncio.open_connection() <open_connection>`. 922 923 924.. coroutinemethod:: loop.sock_accept(sock) 925 926 Accept a connection. Modeled after the blocking 927 :meth:`socket.accept() <socket.socket.accept>` method. 928 929 The socket must be bound to an address and listening 930 for connections. The return value is a pair ``(conn, address)`` where *conn* 931 is a *new* socket object usable to send and receive data on the connection, 932 and *address* is the address bound to the socket on the other end of the 933 connection. 934 935 *sock* must be a non-blocking socket. 936 937 .. versionchanged:: 3.7 938 Even though the method was always documented as a coroutine 939 method, before Python 3.7 it returned a :class:`Future`. 940 Since Python 3.7, this is an ``async def`` method. 941 942 .. seealso:: 943 944 :meth:`loop.create_server` and :func:`start_server`. 945 946.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \ 947 *, fallback=True) 948 949 Send a file using high-performance :mod:`os.sendfile` if possible. 950 Return the total number of bytes sent. 951 952 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`. 953 954 *sock* must be a non-blocking :const:`socket.SOCK_STREAM` 955 :class:`~socket.socket`. 956 957 *file* must be a regular file object open in binary mode. 958 959 *offset* tells from where to start reading the file. If specified, 960 *count* is the total number of bytes to transmit as opposed to 961 sending the file until EOF is reached. File position is always updated, 962 even when this method raises an error, and 963 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual 964 number of bytes sent. 965 966 *fallback*, when set to ``True``, makes asyncio manually read and send 967 the file when the platform does not support the sendfile syscall 968 (e.g. Windows or SSL socket on Unix). 969 970 Raise :exc:`SendfileNotAvailableError` if the system does not support 971 *sendfile* syscall and *fallback* is ``False``. 972 973 *sock* must be a non-blocking socket. 974 975 .. versionadded:: 3.7 976 977 978DNS 979^^^ 980 981.. coroutinemethod:: loop.getaddrinfo(host, port, *, family=0, \ 982 type=0, proto=0, flags=0) 983 984 Asynchronous version of :meth:`socket.getaddrinfo`. 985 986.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0) 987 988 Asynchronous version of :meth:`socket.getnameinfo`. 989 990.. versionchanged:: 3.7 991 Both *getaddrinfo* and *getnameinfo* methods were always documented 992 to return a coroutine, but prior to Python 3.7 they were, in fact, 993 returning :class:`asyncio.Future` objects. Starting with Python 3.7 994 both methods are coroutines. 995 996 997Working with pipes 998^^^^^^^^^^^^^^^^^^ 999 1000.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe) 1001 1002 Register the read end of *pipe* in the event loop. 1003 1004 *protocol_factory* must be a callable returning an 1005 :ref:`asyncio protocol <asyncio-protocol>` implementation. 1006 1007 *pipe* is a :term:`file-like object <file object>`. 1008 1009 Return pair ``(transport, protocol)``, where *transport* supports 1010 the :class:`ReadTransport` interface and *protocol* is an object 1011 instantiated by the *protocol_factory*. 1012 1013 With :class:`SelectorEventLoop` event loop, the *pipe* is set to 1014 non-blocking mode. 1015 1016.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe) 1017 1018 Register the write end of *pipe* in the event loop. 1019 1020 *protocol_factory* must be a callable returning an 1021 :ref:`asyncio protocol <asyncio-protocol>` implementation. 1022 1023 *pipe* is :term:`file-like object <file object>`. 1024 1025 Return pair ``(transport, protocol)``, where *transport* supports 1026 :class:`WriteTransport` interface and *protocol* is an object 1027 instantiated by the *protocol_factory*. 1028 1029 With :class:`SelectorEventLoop` event loop, the *pipe* is set to 1030 non-blocking mode. 1031 1032.. note:: 1033 1034 :class:`SelectorEventLoop` does not support the above methods on 1035 Windows. Use :class:`ProactorEventLoop` instead for Windows. 1036 1037.. seealso:: 1038 1039 The :meth:`loop.subprocess_exec` and 1040 :meth:`loop.subprocess_shell` methods. 1041 1042 1043Unix signals 1044^^^^^^^^^^^^ 1045 1046.. method:: loop.add_signal_handler(signum, callback, *args) 1047 1048 Set *callback* as the handler for the *signum* signal. 1049 1050 The callback will be invoked by *loop*, along with other queued callbacks 1051 and runnable coroutines of that event loop. Unlike signal handlers 1052 registered using :func:`signal.signal`, a callback registered with this 1053 function is allowed to interact with the event loop. 1054 1055 Raise :exc:`ValueError` if the signal number is invalid or uncatchable. 1056 Raise :exc:`RuntimeError` if there is a problem setting up the handler. 1057 1058 Use :func:`functools.partial` :ref:`to pass keyword arguments 1059 <asyncio-pass-keywords>` to *callback*. 1060 1061 Like :func:`signal.signal`, this function must be invoked in the main 1062 thread. 1063 1064.. method:: loop.remove_signal_handler(sig) 1065 1066 Remove the handler for the *sig* signal. 1067 1068 Return ``True`` if the signal handler was removed, or ``False`` if 1069 no handler was set for the given signal. 1070 1071 .. availability:: Unix. 1072 1073.. seealso:: 1074 1075 The :mod:`signal` module. 1076 1077 1078Executing code in thread or process pools 1079^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1080 1081.. awaitablemethod:: loop.run_in_executor(executor, func, *args) 1082 1083 Arrange for *func* to be called in the specified executor. 1084 1085 The *executor* argument should be an :class:`concurrent.futures.Executor` 1086 instance. The default executor is used if *executor* is ``None``. 1087 1088 Example:: 1089 1090 import asyncio 1091 import concurrent.futures 1092 1093 def blocking_io(): 1094 # File operations (such as logging) can block the 1095 # event loop: run them in a thread pool. 1096 with open('/dev/urandom', 'rb') as f: 1097 return f.read(100) 1098 1099 def cpu_bound(): 1100 # CPU-bound operations will block the event loop: 1101 # in general it is preferable to run them in a 1102 # process pool. 1103 return sum(i * i for i in range(10 ** 7)) 1104 1105 async def main(): 1106 loop = asyncio.get_running_loop() 1107 1108 ## Options: 1109 1110 # 1. Run in the default loop's executor: 1111 result = await loop.run_in_executor( 1112 None, blocking_io) 1113 print('default thread pool', result) 1114 1115 # 2. Run in a custom thread pool: 1116 with concurrent.futures.ThreadPoolExecutor() as pool: 1117 result = await loop.run_in_executor( 1118 pool, blocking_io) 1119 print('custom thread pool', result) 1120 1121 # 3. Run in a custom process pool: 1122 with concurrent.futures.ProcessPoolExecutor() as pool: 1123 result = await loop.run_in_executor( 1124 pool, cpu_bound) 1125 print('custom process pool', result) 1126 1127 asyncio.run(main()) 1128 1129 This method returns a :class:`asyncio.Future` object. 1130 1131 Use :func:`functools.partial` :ref:`to pass keyword arguments 1132 <asyncio-pass-keywords>` to *func*. 1133 1134 .. versionchanged:: 3.5.3 1135 :meth:`loop.run_in_executor` no longer configures the 1136 ``max_workers`` of the thread pool executor it creates, instead 1137 leaving it up to the thread pool executor 1138 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the 1139 default. 1140 1141.. method:: loop.set_default_executor(executor) 1142 1143 Set *executor* as the default executor used by :meth:`run_in_executor`. 1144 *executor* should be an instance of 1145 :class:`~concurrent.futures.ThreadPoolExecutor`. 1146 1147 .. deprecated:: 3.8 1148 Using an executor that is not an instance of 1149 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and 1150 will trigger an error in Python 3.9. 1151 1152 *executor* must be an instance of 1153 :class:`concurrent.futures.ThreadPoolExecutor`. 1154 1155 1156Error Handling API 1157^^^^^^^^^^^^^^^^^^ 1158 1159Allows customizing how exceptions are handled in the event loop. 1160 1161.. method:: loop.set_exception_handler(handler) 1162 1163 Set *handler* as the new event loop exception handler. 1164 1165 If *handler* is ``None``, the default exception handler will 1166 be set. Otherwise, *handler* must be a callable with the signature 1167 matching ``(loop, context)``, where ``loop`` 1168 is a reference to the active event loop, and ``context`` 1169 is a ``dict`` object containing the details of the exception 1170 (see :meth:`call_exception_handler` documentation for details 1171 about context). 1172 1173.. method:: loop.get_exception_handler() 1174 1175 Return the current exception handler, or ``None`` if no custom 1176 exception handler was set. 1177 1178 .. versionadded:: 3.5.2 1179 1180.. method:: loop.default_exception_handler(context) 1181 1182 Default exception handler. 1183 1184 This is called when an exception occurs and no exception 1185 handler is set. This can be called by a custom exception 1186 handler that wants to defer to the default handler behavior. 1187 1188 *context* parameter has the same meaning as in 1189 :meth:`call_exception_handler`. 1190 1191.. method:: loop.call_exception_handler(context) 1192 1193 Call the current event loop exception handler. 1194 1195 *context* is a ``dict`` object containing the following keys 1196 (new keys may be introduced in future Python versions): 1197 1198 * 'message': Error message; 1199 * 'exception' (optional): Exception object; 1200 * 'future' (optional): :class:`asyncio.Future` instance; 1201 * 'task' (optional): :class:`asyncio.Task` instance; 1202 * 'handle' (optional): :class:`asyncio.Handle` instance; 1203 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance; 1204 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance; 1205 * 'socket' (optional): :class:`socket.socket` instance; 1206 * 'asyncgen' (optional): Asynchronous generator that caused 1207 the exception. 1208 1209 .. note:: 1210 1211 This method should not be overloaded in subclassed 1212 event loops. For custom exception handling, use 1213 the :meth:`set_exception_handler()` method. 1214 1215Enabling debug mode 1216^^^^^^^^^^^^^^^^^^^ 1217 1218.. method:: loop.get_debug() 1219 1220 Get the debug mode (:class:`bool`) of the event loop. 1221 1222 The default value is ``True`` if the environment variable 1223 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False`` 1224 otherwise. 1225 1226.. method:: loop.set_debug(enabled: bool) 1227 1228 Set the debug mode of the event loop. 1229 1230 .. versionchanged:: 3.7 1231 1232 The new :ref:`Python Development Mode <devmode>` can now also be used 1233 to enable the debug mode. 1234 1235.. seealso:: 1236 1237 The :ref:`debug mode of asyncio <asyncio-debug-mode>`. 1238 1239 1240Running Subprocesses 1241^^^^^^^^^^^^^^^^^^^^ 1242 1243Methods described in this subsections are low-level. In regular 1244async/await code consider using the high-level 1245:func:`asyncio.create_subprocess_shell` and 1246:func:`asyncio.create_subprocess_exec` convenience functions instead. 1247 1248.. note:: 1249 1250 On Windows, the default event loop :class:`ProactorEventLoop` supports 1251 subprocesses, whereas :class:`SelectorEventLoop` does not. See 1252 :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>` for 1253 details. 1254 1255.. coroutinemethod:: loop.subprocess_exec(protocol_factory, *args, \ 1256 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ 1257 stderr=subprocess.PIPE, **kwargs) 1258 1259 Create a subprocess from one or more string arguments specified by 1260 *args*. 1261 1262 *args* must be a list of strings represented by: 1263 1264 * :class:`str`; 1265 * or :class:`bytes`, encoded to the 1266 :ref:`filesystem encoding <filesystem-encoding>`. 1267 1268 The first string specifies the program executable, 1269 and the remaining strings specify the arguments. Together, string 1270 arguments form the ``argv`` of the program. 1271 1272 This is similar to the standard library :class:`subprocess.Popen` 1273 class called with ``shell=False`` and the list of strings passed as 1274 the first argument; however, where :class:`~subprocess.Popen` takes 1275 a single argument which is list of strings, *subprocess_exec* 1276 takes multiple string arguments. 1277 1278 The *protocol_factory* must be a callable returning a subclass of the 1279 :class:`asyncio.SubprocessProtocol` class. 1280 1281 Other parameters: 1282 1283 * *stdin* can be any of these: 1284 1285 * a file-like object representing a pipe to be connected to the 1286 subprocess's standard input stream using 1287 :meth:`~loop.connect_write_pipe` 1288 * the :const:`subprocess.PIPE` constant (default) which will create a new 1289 pipe and connect it, 1290 * the value ``None`` which will make the subprocess inherit the file 1291 descriptor from this process 1292 * the :const:`subprocess.DEVNULL` constant which indicates that the 1293 special :data:`os.devnull` file will be used 1294 1295 * *stdout* can be any of these: 1296 1297 * a file-like object representing a pipe to be connected to the 1298 subprocess's standard output stream using 1299 :meth:`~loop.connect_write_pipe` 1300 * the :const:`subprocess.PIPE` constant (default) which will create a new 1301 pipe and connect it, 1302 * the value ``None`` which will make the subprocess inherit the file 1303 descriptor from this process 1304 * the :const:`subprocess.DEVNULL` constant which indicates that the 1305 special :data:`os.devnull` file will be used 1306 1307 * *stderr* can be any of these: 1308 1309 * a file-like object representing a pipe to be connected to the 1310 subprocess's standard error stream using 1311 :meth:`~loop.connect_write_pipe` 1312 * the :const:`subprocess.PIPE` constant (default) which will create a new 1313 pipe and connect it, 1314 * the value ``None`` which will make the subprocess inherit the file 1315 descriptor from this process 1316 * the :const:`subprocess.DEVNULL` constant which indicates that the 1317 special :data:`os.devnull` file will be used 1318 * the :const:`subprocess.STDOUT` constant which will connect the standard 1319 error stream to the process' standard output stream 1320 1321 * All other keyword arguments are passed to :class:`subprocess.Popen` 1322 without interpretation, except for *bufsize*, *universal_newlines*, 1323 *shell*, *text*, *encoding* and *errors*, which should not be specified 1324 at all. 1325 1326 The ``asyncio`` subprocess API does not support decoding the streams 1327 as text. :func:`bytes.decode` can be used to convert the bytes returned 1328 from the stream to text. 1329 1330 See the constructor of the :class:`subprocess.Popen` class 1331 for documentation on other arguments. 1332 1333 Returns a pair of ``(transport, protocol)``, where *transport* 1334 conforms to the :class:`asyncio.SubprocessTransport` base class and 1335 *protocol* is an object instantiated by the *protocol_factory*. 1336 1337.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, *, \ 1338 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ 1339 stderr=subprocess.PIPE, **kwargs) 1340 1341 Create a subprocess from *cmd*, which can be a :class:`str` or a 1342 :class:`bytes` string encoded to the 1343 :ref:`filesystem encoding <filesystem-encoding>`, 1344 using the platform's "shell" syntax. 1345 1346 This is similar to the standard library :class:`subprocess.Popen` 1347 class called with ``shell=True``. 1348 1349 The *protocol_factory* must be a callable returning a subclass of the 1350 :class:`SubprocessProtocol` class. 1351 1352 See :meth:`~loop.subprocess_exec` for more details about 1353 the remaining arguments. 1354 1355 Returns a pair of ``(transport, protocol)``, where *transport* 1356 conforms to the :class:`SubprocessTransport` base class and 1357 *protocol* is an object instantiated by the *protocol_factory*. 1358 1359.. note:: 1360 It is the application's responsibility to ensure that all whitespace 1361 and special characters are quoted appropriately to avoid `shell injection 1362 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_ 1363 vulnerabilities. The :func:`shlex.quote` function can be used to 1364 properly escape whitespace and special characters in strings that 1365 are going to be used to construct shell commands. 1366 1367 1368Callback Handles 1369================ 1370 1371.. class:: Handle 1372 1373 A callback wrapper object returned by :meth:`loop.call_soon`, 1374 :meth:`loop.call_soon_threadsafe`. 1375 1376 .. method:: cancel() 1377 1378 Cancel the callback. If the callback has already been canceled 1379 or executed, this method has no effect. 1380 1381 .. method:: cancelled() 1382 1383 Return ``True`` if the callback was cancelled. 1384 1385 .. versionadded:: 3.7 1386 1387.. class:: TimerHandle 1388 1389 A callback wrapper object returned by :meth:`loop.call_later`, 1390 and :meth:`loop.call_at`. 1391 1392 This class is a subclass of :class:`Handle`. 1393 1394 .. method:: when() 1395 1396 Return a scheduled callback time as :class:`float` seconds. 1397 1398 The time is an absolute timestamp, using the same time 1399 reference as :meth:`loop.time`. 1400 1401 .. versionadded:: 3.7 1402 1403 1404Server Objects 1405============== 1406 1407Server objects are created by :meth:`loop.create_server`, 1408:meth:`loop.create_unix_server`, :func:`start_server`, 1409and :func:`start_unix_server` functions. 1410 1411Do not instantiate the class directly. 1412 1413.. class:: Server 1414 1415 *Server* objects are asynchronous context managers. When used in an 1416 ``async with`` statement, it's guaranteed that the Server object is 1417 closed and not accepting new connections when the ``async with`` 1418 statement is completed:: 1419 1420 srv = await loop.create_server(...) 1421 1422 async with srv: 1423 # some code 1424 1425 # At this point, srv is closed and no longer accepts new connections. 1426 1427 1428 .. versionchanged:: 3.7 1429 Server object is an asynchronous context manager since Python 3.7. 1430 1431 .. method:: close() 1432 1433 Stop serving: close listening sockets and set the :attr:`sockets` 1434 attribute to ``None``. 1435 1436 The sockets that represent existing incoming client connections 1437 are left open. 1438 1439 The server is closed asynchronously, use the :meth:`wait_closed` 1440 coroutine to wait until the server is closed. 1441 1442 .. method:: get_loop() 1443 1444 Return the event loop associated with the server object. 1445 1446 .. versionadded:: 3.7 1447 1448 .. coroutinemethod:: start_serving() 1449 1450 Start accepting connections. 1451 1452 This method is idempotent, so it can be called when 1453 the server is already being serving. 1454 1455 The *start_serving* keyword-only parameter to 1456 :meth:`loop.create_server` and 1457 :meth:`asyncio.start_server` allows creating a Server object 1458 that is not accepting connections initially. In this case 1459 ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used 1460 to make the Server start accepting connections. 1461 1462 .. versionadded:: 3.7 1463 1464 .. coroutinemethod:: serve_forever() 1465 1466 Start accepting connections until the coroutine is cancelled. 1467 Cancellation of ``serve_forever`` task causes the server 1468 to be closed. 1469 1470 This method can be called if the server is already accepting 1471 connections. Only one ``serve_forever`` task can exist per 1472 one *Server* object. 1473 1474 Example:: 1475 1476 async def client_connected(reader, writer): 1477 # Communicate with the client with 1478 # reader/writer streams. For example: 1479 await reader.readline() 1480 1481 async def main(host, port): 1482 srv = await asyncio.start_server( 1483 client_connected, host, port) 1484 await srv.serve_forever() 1485 1486 asyncio.run(main('127.0.0.1', 0)) 1487 1488 .. versionadded:: 3.7 1489 1490 .. method:: is_serving() 1491 1492 Return ``True`` if the server is accepting new connections. 1493 1494 .. versionadded:: 3.7 1495 1496 .. coroutinemethod:: wait_closed() 1497 1498 Wait until the :meth:`close` method completes. 1499 1500 .. attribute:: sockets 1501 1502 List of :class:`socket.socket` objects the server is listening on. 1503 1504 .. versionchanged:: 3.7 1505 Prior to Python 3.7 ``Server.sockets`` used to return an 1506 internal list of server sockets directly. In 3.7 a copy 1507 of that list is returned. 1508 1509 1510.. _asyncio-event-loops: 1511 1512Event Loop Implementations 1513========================== 1514 1515asyncio ships with two different event loop implementations: 1516:class:`SelectorEventLoop` and :class:`ProactorEventLoop`. 1517 1518By default asyncio is configured to use :class:`SelectorEventLoop` 1519on Unix and :class:`ProactorEventLoop` on Windows. 1520 1521 1522.. class:: SelectorEventLoop 1523 1524 An event loop based on the :mod:`selectors` module. 1525 1526 Uses the most efficient *selector* available for the given 1527 platform. It is also possible to manually configure the 1528 exact selector implementation to be used:: 1529 1530 import asyncio 1531 import selectors 1532 1533 selector = selectors.SelectSelector() 1534 loop = asyncio.SelectorEventLoop(selector) 1535 asyncio.set_event_loop(loop) 1536 1537 1538 .. availability:: Unix, Windows. 1539 1540 1541.. class:: ProactorEventLoop 1542 1543 An event loop for Windows that uses "I/O Completion Ports" (IOCP). 1544 1545 .. availability:: Windows. 1546 1547 .. seealso:: 1548 1549 `MSDN documentation on I/O Completion Ports 1550 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_. 1551 1552 1553.. class:: AbstractEventLoop 1554 1555 Abstract base class for asyncio-compliant event loops. 1556 1557 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all 1558 methods that an alternative implementation of ``AbstractEventLoop`` 1559 should have defined. 1560 1561 1562Examples 1563======== 1564 1565Note that all examples in this section **purposefully** show how 1566to use the low-level event loop APIs, such as :meth:`loop.run_forever` 1567and :meth:`loop.call_soon`. Modern asyncio applications rarely 1568need to be written this way; consider using the high-level functions 1569like :func:`asyncio.run`. 1570 1571 1572.. _asyncio_example_lowlevel_helloworld: 1573 1574Hello World with call_soon() 1575^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1576 1577An example using the :meth:`loop.call_soon` method to schedule a 1578callback. The callback displays ``"Hello World"`` and then stops the 1579event loop:: 1580 1581 import asyncio 1582 1583 def hello_world(loop): 1584 """A callback to print 'Hello World' and stop the event loop""" 1585 print('Hello World') 1586 loop.stop() 1587 1588 loop = asyncio.get_event_loop() 1589 1590 # Schedule a call to hello_world() 1591 loop.call_soon(hello_world, loop) 1592 1593 # Blocking call interrupted by loop.stop() 1594 try: 1595 loop.run_forever() 1596 finally: 1597 loop.close() 1598 1599.. seealso:: 1600 1601 A similar :ref:`Hello World <coroutine>` 1602 example created with a coroutine and the :func:`run` function. 1603 1604 1605.. _asyncio_example_call_later: 1606 1607Display the current date with call_later() 1608^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1609 1610An example of a callback displaying the current date every second. The 1611callback uses the :meth:`loop.call_later` method to reschedule itself 1612after 5 seconds, and then stops the event loop:: 1613 1614 import asyncio 1615 import datetime 1616 1617 def display_date(end_time, loop): 1618 print(datetime.datetime.now()) 1619 if (loop.time() + 1.0) < end_time: 1620 loop.call_later(1, display_date, end_time, loop) 1621 else: 1622 loop.stop() 1623 1624 loop = asyncio.get_event_loop() 1625 1626 # Schedule the first call to display_date() 1627 end_time = loop.time() + 5.0 1628 loop.call_soon(display_date, end_time, loop) 1629 1630 # Blocking call interrupted by loop.stop() 1631 try: 1632 loop.run_forever() 1633 finally: 1634 loop.close() 1635 1636.. seealso:: 1637 1638 A similar :ref:`current date <asyncio_example_sleep>` example 1639 created with a coroutine and the :func:`run` function. 1640 1641 1642.. _asyncio_example_watch_fd: 1643 1644Watch a file descriptor for read events 1645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1646 1647Wait until a file descriptor received some data using the 1648:meth:`loop.add_reader` method and then close the event loop:: 1649 1650 import asyncio 1651 from socket import socketpair 1652 1653 # Create a pair of connected file descriptors 1654 rsock, wsock = socketpair() 1655 1656 loop = asyncio.get_event_loop() 1657 1658 def reader(): 1659 data = rsock.recv(100) 1660 print("Received:", data.decode()) 1661 1662 # We are done: unregister the file descriptor 1663 loop.remove_reader(rsock) 1664 1665 # Stop the event loop 1666 loop.stop() 1667 1668 # Register the file descriptor for read event 1669 loop.add_reader(rsock, reader) 1670 1671 # Simulate the reception of data from the network 1672 loop.call_soon(wsock.send, 'abc'.encode()) 1673 1674 try: 1675 # Run the event loop 1676 loop.run_forever() 1677 finally: 1678 # We are done. Close sockets and the event loop. 1679 rsock.close() 1680 wsock.close() 1681 loop.close() 1682 1683.. seealso:: 1684 1685 * A similar :ref:`example <asyncio_example_create_connection>` 1686 using transports, protocols, and the 1687 :meth:`loop.create_connection` method. 1688 1689 * Another similar :ref:`example <asyncio_example_create_connection-streams>` 1690 using the high-level :func:`asyncio.open_connection` function 1691 and streams. 1692 1693 1694.. _asyncio_example_unix_signals: 1695 1696Set signal handlers for SIGINT and SIGTERM 1697^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1698 1699(This ``signals`` example only works on Unix.) 1700 1701Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` 1702using the :meth:`loop.add_signal_handler` method:: 1703 1704 import asyncio 1705 import functools 1706 import os 1707 import signal 1708 1709 def ask_exit(signame, loop): 1710 print("got signal %s: exit" % signame) 1711 loop.stop() 1712 1713 async def main(): 1714 loop = asyncio.get_running_loop() 1715 1716 for signame in {'SIGINT', 'SIGTERM'}: 1717 loop.add_signal_handler( 1718 getattr(signal, signame), 1719 functools.partial(ask_exit, signame, loop)) 1720 1721 await asyncio.sleep(3600) 1722 1723 print("Event loop running for 1 hour, press Ctrl+C to interrupt.") 1724 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.") 1725 1726 asyncio.run(main()) 1727