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