summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fasyncio-eventloop.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/library%2Fasyncio-eventloop.html')
-rw-r--r--devdocs/python~3.12/library%2Fasyncio-eventloop.html449
1 files changed, 449 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fasyncio-eventloop.html b/devdocs/python~3.12/library%2Fasyncio-eventloop.html
new file mode 100644
index 00000000..a06dce1c
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fasyncio-eventloop.html
@@ -0,0 +1,449 @@
+ <span id="asyncio-event-loop"></span><h1>Event Loop</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/events.py">Lib/asyncio/events.py</a>, <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a></p> <h4 class="rubric">Preface</h4> <p>The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.</p> <p>Application developers should typically use the high-level asyncio functions, such as <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a>, and should rarely need to reference the loop object or call its methods. This section is intended mostly for authors of lower-level code, libraries, and frameworks, who need finer control over the event loop behavior.</p> <h4 class="rubric">Obtaining the Event Loop</h4> <p>The following low-level functions can be used to get, set, or create an event loop:</p> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.get_running_loop">
+<code>asyncio.get_running_loop()</code> </dt> <dd>
+<p>Return the running event loop in the current OS thread.</p> <p>Raise a <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> if there is no running event loop.</p> <p>This function can only be called from a coroutine or a callback.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.get_event_loop">
+<code>asyncio.get_event_loop()</code> </dt> <dd>
+<p>Get the current event loop.</p> <p>When called from a coroutine or a callback (e.g. scheduled with call_soon or similar API), this function will always return the running event loop.</p> <p>If there is no running event loop set, the function will return the result of the <code>get_event_loop_policy().get_event_loop()</code> call.</p> <p>Because this function has rather complex behavior (especially when custom event loop policies are in use), using the <a class="reference internal" href="#asyncio.get_running_loop" title="asyncio.get_running_loop"><code>get_running_loop()</code></a> function is preferred to <a class="reference internal" href="#asyncio.get_event_loop" title="asyncio.get_event_loop"><code>get_event_loop()</code></a> in coroutines and callbacks.</p> <p>As noted above, consider using the higher-level <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a> function, instead of using these lower level functions to manually create and close an event loop.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>Deprecation warning is emitted if there is no current event loop. In some future Python release this will become an error.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.set_event_loop">
+<code>asyncio.set_event_loop(loop)</code> </dt> <dd>
+<p>Set <em>loop</em> as the current event loop for the current OS thread.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.new_event_loop">
+<code>asyncio.new_event_loop()</code> </dt> <dd>
+<p>Create and return a new event loop object.</p> </dd>
+</dl> <p>Note that the behaviour of <a class="reference internal" href="#asyncio.get_event_loop" title="asyncio.get_event_loop"><code>get_event_loop()</code></a>, <a class="reference internal" href="#asyncio.set_event_loop" title="asyncio.set_event_loop"><code>set_event_loop()</code></a>, and <a class="reference internal" href="#asyncio.new_event_loop" title="asyncio.new_event_loop"><code>new_event_loop()</code></a> functions can be altered by <a class="reference internal" href="asyncio-policy#asyncio-policies"><span class="std std-ref">setting a custom event loop policy</span></a>.</p> <h4 class="rubric">Contents</h4> <p>This documentation page contains the following sections:</p> <ul class="simple"> <li>The <a class="reference internal" href="#event-loop-methods">Event Loop Methods</a> section is the reference documentation of the event loop APIs;</li> <li>The <a class="reference internal" href="#callback-handles">Callback Handles</a> section documents the <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code>Handle</code></a> and <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code>TimerHandle</code></a> instances which are returned from scheduling methods such as <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a> and <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code>loop.call_later()</code></a>;</li> <li>The <a class="reference internal" href="#server-objects">Server Objects</a> section documents types returned from event loop methods like <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a>;</li> <li>The <a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a> section documents the <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a> classes;</li> <li>The <a class="reference internal" href="#examples">Examples</a> section showcases how to work with some event loop APIs.</li> </ul> <section id="event-loop-methods"> <span id="asyncio-event-loop-methods"></span><h2>Event Loop Methods</h2> <p>Event loops have <strong>low-level</strong> APIs for the following:</p> <ul class="simple"> <li><a class="reference internal" href="#running-and-stopping-the-loop" id="id1">Running and stopping the loop</a></li> <li><a class="reference internal" href="#scheduling-callbacks" id="id2">Scheduling callbacks</a></li> <li><a class="reference internal" href="#scheduling-delayed-callbacks" id="id3">Scheduling delayed callbacks</a></li> <li><a class="reference internal" href="#creating-futures-and-tasks" id="id4">Creating Futures and Tasks</a></li> <li><a class="reference internal" href="#opening-network-connections" id="id5">Opening network connections</a></li> <li><a class="reference internal" href="#creating-network-servers" id="id6">Creating network servers</a></li> <li><a class="reference internal" href="#transferring-files" id="id7">Transferring files</a></li> <li><a class="reference internal" href="#tls-upgrade" id="id8">TLS Upgrade</a></li> <li><a class="reference internal" href="#watching-file-descriptors" id="id9">Watching file descriptors</a></li> <li><a class="reference internal" href="#working-with-socket-objects-directly" id="id10">Working with socket objects directly</a></li> <li><a class="reference internal" href="#dns" id="id11">DNS</a></li> <li><a class="reference internal" href="#working-with-pipes" id="id12">Working with pipes</a></li> <li><a class="reference internal" href="#unix-signals" id="id13">Unix signals</a></li> <li><a class="reference internal" href="#executing-code-in-thread-or-process-pools" id="id14">Executing code in thread or process pools</a></li> <li><a class="reference internal" href="#error-handling-api" id="id15">Error Handling API</a></li> <li><a class="reference internal" href="#enabling-debug-mode" id="id16">Enabling debug mode</a></li> <li><a class="reference internal" href="#running-subprocesses" id="id17">Running Subprocesses</a></li> </ul> <section id="running-and-stopping-the-loop"> <h3>Running and stopping the loop</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.run_until_complete">
+<code>loop.run_until_complete(future)</code> </dt> <dd>
+<p>Run until the <em>future</em> (an instance of <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a>) has completed.</p> <p>If the argument is a <a class="reference internal" href="asyncio-task#coroutine"><span class="std std-ref">coroutine object</span></a> it is implicitly scheduled to run as a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a>.</p> <p>Return the Future’s result or raise its exception.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.run_forever">
+<code>loop.run_forever()</code> </dt> <dd>
+<p>Run the event loop until <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code>stop()</code></a> is called.</p> <p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code>stop()</code></a> is called before <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code>run_forever()</code></a> is called, the loop will poll the I/O selector once with a timeout of zero, run all callbacks scheduled in response to I/O events (and those that were already scheduled), and then exit.</p> <p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code>stop()</code></a> is called while <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code>run_forever()</code></a> is running, the loop will run the current batch of callbacks and then exit. Note that new callbacks scheduled by callbacks will not run in this case; instead, they will run the next time <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code>run_forever()</code></a> or <a class="reference internal" href="#asyncio.loop.run_until_complete" title="asyncio.loop.run_until_complete"><code>run_until_complete()</code></a> is called.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.stop">
+<code>loop.stop()</code> </dt> <dd>
+<p>Stop the event loop.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.is_running">
+<code>loop.is_running()</code> </dt> <dd>
+<p>Return <code>True</code> if the event loop is currently running.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.is_closed">
+<code>loop.is_closed()</code> </dt> <dd>
+<p>Return <code>True</code> if the event loop was closed.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.close">
+<code>loop.close()</code> </dt> <dd>
+<p>Close the event loop.</p> <p>The loop must not be running when this function is called. Any pending callbacks will be discarded.</p> <p>This method clears all queues and shuts down the executor, but does not wait for the executor to finish.</p> <p>This method is idempotent and irreversible. No other methods should be called after the event loop is closed.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.shutdown_asyncgens">
+<code>coroutine loop.shutdown_asyncgens()</code> </dt> <dd>
+<p>Schedule all currently open <a class="reference internal" href="../glossary#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> objects to close with an <a class="reference internal" href="../reference/expressions#agen.aclose" title="agen.aclose"><code>aclose()</code></a> call. After calling this method, the event loop will issue a warning if a new asynchronous generator is iterated. This should be used to reliably finalize all scheduled asynchronous generators.</p> <p>Note that there is no need to call this function when <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a> is used.</p> <p>Example:</p> <pre data-language="python">try:
+ loop.run_forever()
+finally:
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ loop.close()
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.shutdown_default_executor">
+<code>coroutine loop.shutdown_default_executor(timeout=None)</code> </dt> <dd>
+<p>Schedule the closure of the default executor and wait for it to join all of the threads in the <a class="reference internal" href="concurrent.futures#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a>. Once this method has been called, using the default executor with <a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code>loop.run_in_executor()</code></a> will raise a <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a>.</p> <p>The <em>timeout</em> parameter specifies the amount of time (in <a class="reference internal" href="functions#float" title="float"><code>float</code></a> seconds) the executor will be given to finish joining. With the default, <code>None</code>, the executor is allowed an unlimited amount of time.</p> <p>If the <em>timeout</em> is reached, a <a class="reference internal" href="exceptions#RuntimeWarning" title="RuntimeWarning"><code>RuntimeWarning</code></a> is emitted and the default executor is terminated without waiting for its threads to finish joining.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Do not call this method when using <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a>, as the latter handles default executor shutdown automatically.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>timeout</em> parameter.</p> </div> </dd>
+</dl> </section> <section id="scheduling-callbacks"> <h3>Scheduling callbacks</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.call_soon">
+<code>loop.call_soon(callback, *args, context=None)</code> </dt> <dd>
+<p>Schedule the <em>callback</em> <a class="reference internal" href="../glossary#term-callback"><span class="xref std std-term">callback</span></a> to be called with <em>args</em> arguments at the next iteration of the event loop.</p> <p>Return an instance of <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code>asyncio.Handle</code></a>, which can be used later to cancel the callback.</p> <p>Callbacks are called in the order in which they are registered. Each callback will be called exactly once.</p> <p>The optional keyword-only <em>context</em> argument specifies a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>callback</em> to run in. Callbacks use the current context when no <em>context</em> is provided.</p> <p>Unlike <a class="reference internal" href="#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code>call_soon_threadsafe()</code></a>, this method is not thread-safe.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.call_soon_threadsafe">
+<code>loop.call_soon_threadsafe(callback, *args, context=None)</code> </dt> <dd>
+<p>A thread-safe variant of <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>call_soon()</code></a>. When scheduling callbacks from another thread, this function <em>must</em> be used, since <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>call_soon()</code></a> is not thread-safe.</p> <p>Raises <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> if called on a loop that’s been closed. This can happen on a secondary thread when the main application is shutting down.</p> <p>See the <a class="reference internal" href="asyncio-dev#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a> section of the documentation.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added. See <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for more details.</p> </div> </dd>
+</dl> <div class="admonition note" id="asyncio-pass-keywords"> <p class="admonition-title">Note</p> <p>Most <a class="reference internal" href="asyncio#module-asyncio" title="asyncio: Asynchronous I/O."><code>asyncio</code></a> scheduling functions don’t allow passing keyword arguments. To do that, use <a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a>:</p> <pre data-language="python"># will schedule "print("Hello", flush=True)"
+loop.call_soon(
+ functools.partial(print, "Hello", flush=True))
+</pre> <p>Using partial objects is usually more convenient than using lambdas, as asyncio can render partial objects better in debug and error messages.</p> </div> </section> <section id="scheduling-delayed-callbacks"> <span id="asyncio-delayed-calls"></span><h3>Scheduling delayed callbacks</h3> <p>Event loop provides mechanisms to schedule callback functions to be called at some point in the future. Event loop uses monotonic clocks to track time.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.call_later">
+<code>loop.call_later(delay, callback, *args, context=None)</code> </dt> <dd>
+<p>Schedule <em>callback</em> to be called after the given <em>delay</em> number of seconds (can be either an int or a float).</p> <p>An instance of <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code>asyncio.TimerHandle</code></a> is returned which can be used to cancel the callback.</p> <p><em>callback</em> will be called exactly once. If two callbacks are scheduled for exactly the same time, the order in which they are called is undefined.</p> <p>The optional positional <em>args</em> will be passed to the callback when it is called. If you want the callback to be called with keyword arguments use <a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a>.</p> <p>An optional keyword-only <em>context</em> argument allows specifying a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>callback</em> to run in. The current context is used when no <em>context</em> is provided.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added. See <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for more details.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>In Python 3.7 and earlier with the default event loop implementation, the <em>delay</em> could not exceed one day. This has been fixed in Python 3.8.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.call_at">
+<code>loop.call_at(when, callback, *args, context=None)</code> </dt> <dd>
+<p>Schedule <em>callback</em> to be called at the given absolute timestamp <em>when</em> (an int or a float), using the same time reference as <a class="reference internal" href="#asyncio.loop.time" title="asyncio.loop.time"><code>loop.time()</code></a>.</p> <p>This method’s behavior is the same as <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code>call_later()</code></a>.</p> <p>An instance of <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code>asyncio.TimerHandle</code></a> is returned which can be used to cancel the callback.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>context</em> keyword-only parameter was added. See <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0567/"><strong>PEP 567</strong></a> for more details.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>In Python 3.7 and earlier with the default event loop implementation, the difference between <em>when</em> and the current time could not exceed one day. This has been fixed in Python 3.8.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.time">
+<code>loop.time()</code> </dt> <dd>
+<p>Return the current time, as a <a class="reference internal" href="functions#float" title="float"><code>float</code></a> value, according to the event loop’s internal monotonic clock.</p> </dd>
+</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>In Python 3.7 and earlier timeouts (relative <em>delay</em> or absolute <em>when</em>) should not exceed one day. This has been fixed in Python 3.8.</p> </div> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-task#asyncio.sleep" title="asyncio.sleep"><code>asyncio.sleep()</code></a> function.</p> </div> </section> <section id="creating-futures-and-tasks"> <h3>Creating Futures and Tasks</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_future">
+<code>loop.create_future()</code> </dt> <dd>
+<p>Create an <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a> object attached to the event loop.</p> <p>This is the preferred way to create Futures in asyncio. This lets third-party event loops provide alternative implementations of the Future object (with better performance or instrumentation).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_task">
+<code>loop.create_task(coro, *, name=None, context=None)</code> </dt> <dd>
+<p>Schedule the execution of <a class="reference internal" href="asyncio-task#coroutine"><span class="std std-ref">coroutine</span></a> <em>coro</em>. Return a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a> object.</p> <p>Third-party event loops can use their own subclass of <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a> for interoperability. In this case, the result type is a subclass of <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a>.</p> <p>If the <em>name</em> argument is provided and not <code>None</code>, it is set as the name of the task using <a class="reference internal" href="asyncio-task#asyncio.Task.set_name" title="asyncio.Task.set_name"><code>Task.set_name()</code></a>.</p> <p>An optional keyword-only <em>context</em> argument allows specifying a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>coro</em> to run in. The current context copy is created when no <em>context</em> is provided.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.set_task_factory">
+<code>loop.set_task_factory(factory)</code> </dt> <dd>
+<p>Set a task factory that will be used by <a class="reference internal" href="#asyncio.loop.create_task" title="asyncio.loop.create_task"><code>loop.create_task()</code></a>.</p> <p>If <em>factory</em> is <code>None</code> the default task factory will be set. Otherwise, <em>factory</em> must be a <em>callable</em> with the signature matching <code>(loop, coro, context=None)</code>, where <em>loop</em> is a reference to the active event loop, and <em>coro</em> is a coroutine object. The callable must return a <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a>-compatible object.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.get_task_factory">
+<code>loop.get_task_factory()</code> </dt> <dd>
+<p>Return a task factory or <code>None</code> if the default one is in use.</p> </dd>
+</dl> </section> <section id="opening-network-connections"> <h3>Opening network connections</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_connection">
+<code>coroutine loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None, all_errors=False)</code> </dt> <dd>
+<p>Open a streaming transport connection to a given address specified by <em>host</em> and <em>port</em>.</p> <p>The socket family can be either <a class="reference internal" href="socket#socket.AF_INET" title="socket.AF_INET"><code>AF_INET</code></a> or <a class="reference internal" href="socket#socket.AF_INET6" title="socket.AF_INET6"><code>AF_INET6</code></a> depending on <em>host</em> (or the <em>family</em> argument, if provided).</p> <p>The socket type will be <a class="reference internal" href="socket#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code>SOCK_STREAM</code></a>.</p> <p><em>protocol_factory</em> must be a callable returning an <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p> <p>This method will try to establish the connection in the background. When successful, it returns a <code>(transport, protocol)</code> pair.</p> <p>The chronological synopsis of the underlying operation is as follows:</p> <ol class="arabic simple"> <li>The connection is established and a <a class="reference internal" href="asyncio-protocol#asyncio-transport"><span class="std std-ref">transport</span></a> is created for it.</li> <li>
+<em>protocol_factory</em> is called without arguments and is expected to return a <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">protocol</span></a> instance.</li> <li>The protocol instance is coupled with the transport by calling its <a class="reference internal" href="asyncio-protocol#asyncio.BaseProtocol.connection_made" title="asyncio.BaseProtocol.connection_made"><code>connection_made()</code></a> method.</li> <li>A <code>(transport, protocol)</code> tuple is returned on success.</li> </ol> <p>The created transport is an implementation-dependent bidirectional stream.</p> <p>Other arguments:</p> <ul> <li>
+<p><em>ssl</em>: if given and not false, a SSL/TLS transport is created (by default a plain TCP transport is created). If <em>ssl</em> is a <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>ssl.SSLContext</code></a> object, this context is used to create the transport; if <em>ssl</em> is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, a default context returned from <a class="reference internal" href="ssl#ssl.create_default_context" title="ssl.create_default_context"><code>ssl.create_default_context()</code></a> is used.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="ssl#ssl-security"><span class="std std-ref">SSL/TLS security considerations</span></a></p> </div> </li> <li>
+<em>server_hostname</em> sets or overrides the hostname that the target server’s certificate will be matched against. Should only be passed if <em>ssl</em> is not <code>None</code>. By default the value of the <em>host</em> argument is used. If <em>host</em> is empty, there is no default and you must pass a value for <em>server_hostname</em>. If <em>server_hostname</em> is an empty string, hostname matching is disabled (which is a serious security risk, allowing for potential man-in-the-middle attacks).</li> <li>
+<em>family</em>, <em>proto</em>, <em>flags</em> are the optional address family, protocol and flags to be passed through to getaddrinfo() for <em>host</em> resolution. If given, these should all be integers from the corresponding <a class="reference internal" href="socket#module-socket" title="socket: Low-level networking interface."><code>socket</code></a> module constants.</li> <li>
+<em>happy_eyeballs_delay</em>, if given, enables Happy Eyeballs for this connection. It should be a floating-point number representing the amount of time in seconds to wait for a connection attempt to complete, before starting the next attempt in parallel. This is the “Connection Attempt Delay” as defined in <span class="target" id="index-3"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc8305.html"><strong>RFC 8305</strong></a>. A sensible default value recommended by the RFC is <code>0.25</code> (250 milliseconds).</li> <li>
+<em>interleave</em> controls address reordering when a host name resolves to multiple IP addresses. If <code>0</code> or unspecified, no reordering is done, and addresses are tried in the order returned by <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>getaddrinfo()</code></a>. If a positive integer is specified, the addresses are interleaved by address family, and the given integer is interpreted as “First Address Family Count” as defined in <span class="target" id="index-4"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc8305.html"><strong>RFC 8305</strong></a>. The default is <code>0</code> if <em>happy_eyeballs_delay</em> is not specified, and <code>1</code> if it is.</li> <li>
+<p><em>sock</em>, if given, should be an existing, already connected <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> object to be used by the transport. If <em>sock</em> is given, none of <em>host</em>, <em>port</em>, <em>family</em>, <em>proto</em>, <em>flags</em>, <em>happy_eyeballs_delay</em>, <em>interleave</em> and <em>local_addr</em> should be specified.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <em>sock</em> argument transfers ownership of the socket to the transport created. To close the socket, call the transport’s <a class="reference internal" href="asyncio-protocol#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code>close()</code></a> method.</p> </div> </li> <li>
+<em>local_addr</em>, if given, is a <code>(local_host, local_port)</code> tuple used to bind the socket locally. The <em>local_host</em> and <em>local_port</em> are looked up using <code>getaddrinfo()</code>, similarly to <em>host</em> and <em>port</em>.</li> <li>
+<em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. <code>60.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. <code>30.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>all_errors</em> determines what exceptions are raised when a connection cannot be created. By default, only a single <code>Exception</code> is raised: the first exception if there is only one or all errors have same message, or a single <code>OSError</code> with the error messages combined. When <code>all_errors</code> is <code>True</code>, an <code>ExceptionGroup</code> will be raised containing all exceptions (even if there is only one).</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added support for SSL/TLS in <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The socket option <a class="reference internal" href="socket#socket-unix-constants"><span class="std std-ref">socket.TCP_NODELAY</span></a> is set by default for all TCP connections.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>happy_eyeballs_delay</em> and <em>interleave</em> parameters.</p> <p>Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. When a server’s IPv4 path and protocol are working, but the server’s IPv6 path and protocol are not working, a dual-stack client application experiences significant connection delay compared to an IPv4-only client. This is undesirable because it causes the dual-stack client to have a worse user experience. This document specifies requirements for algorithms that reduce this user-visible delay and provides an algorithm.</p> <p>For more information: <a class="reference external" href="https://datatracker.ietf.org/doc/html/rfc6555">https://datatracker.ietf.org/doc/html/rfc6555</a></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><em>all_errors</em> was added.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-stream#asyncio.open_connection" title="asyncio.open_connection"><code>open_connection()</code></a> function is a high-level alternative API. It returns a pair of (<a class="reference internal" href="asyncio-stream#asyncio.StreamReader" title="asyncio.StreamReader"><code>StreamReader</code></a>, <a class="reference internal" href="asyncio-stream#asyncio.StreamWriter" title="asyncio.StreamWriter"><code>StreamWriter</code></a>) that can be used directly in async/await code.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_datagram_endpoint">
+<code>coroutine loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_port=None, allow_broadcast=None, sock=None)</code> </dt> <dd>
+<p>Create a datagram connection.</p> <p>The socket family can be either <a class="reference internal" href="socket#socket.AF_INET" title="socket.AF_INET"><code>AF_INET</code></a>, <a class="reference internal" href="socket#socket.AF_INET6" title="socket.AF_INET6"><code>AF_INET6</code></a>, or <a class="reference internal" href="socket#socket.AF_UNIX" title="socket.AF_UNIX"><code>AF_UNIX</code></a>, depending on <em>host</em> (or the <em>family</em> argument, if provided).</p> <p>The socket type will be <a class="reference internal" href="socket#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code>SOCK_DGRAM</code></a>.</p> <p><em>protocol_factory</em> must be a callable returning a <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</p> <p>A tuple of <code>(transport, protocol)</code> is returned on success.</p> <p>Other arguments:</p> <ul> <li>
+<em>local_addr</em>, if given, is a <code>(local_host, local_port)</code> tuple used to bind the socket locally. The <em>local_host</em> and <em>local_port</em> are looked up using <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>getaddrinfo()</code></a>.</li> <li>
+<em>remote_addr</em>, if given, is a <code>(remote_host, remote_port)</code> tuple used to connect the socket to a remote address. The <em>remote_host</em> and <em>remote_port</em> are looked up using <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>getaddrinfo()</code></a>.</li> <li>
+<em>family</em>, <em>proto</em>, <em>flags</em> are the optional address family, protocol and flags to be passed through to <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>getaddrinfo()</code></a> for <em>host</em> resolution. If given, these should all be integers from the corresponding <a class="reference internal" href="socket#module-socket" title="socket: Low-level networking interface."><code>socket</code></a> module constants.</li> <li>
+<em>reuse_port</em> tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows and some Unixes. If the <a class="reference internal" href="socket#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEPORT</span></a> constant is not defined then this capability is unsupported.</li> <li>
+<em>allow_broadcast</em> tells the kernel to allow this endpoint to send messages to the broadcast address.</li> <li>
+<p><em>sock</em> can optionally be specified in order to use a preexisting, already connected, <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> object to be used by the transport. If specified, <em>local_addr</em> and <em>remote_addr</em> should be omitted (must be <a class="reference internal" href="constants#None" title="None"><code>None</code></a>).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <em>sock</em> argument transfers ownership of the socket to the transport created. To close the socket, call the transport’s <a class="reference internal" href="asyncio-protocol#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code>close()</code></a> method.</p> </div> </li> </ul> <p>See <a class="reference internal" href="asyncio-protocol#asyncio-udp-echo-client-protocol"><span class="std std-ref">UDP echo client protocol</span></a> and <a class="reference internal" href="asyncio-protocol#asyncio-udp-echo-server-protocol"><span class="std std-ref">UDP echo server protocol</span></a> examples.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4.4: </span>The <em>family</em>, <em>proto</em>, <em>flags</em>, <em>reuse_address</em>, <em>reuse_port</em>, <em>allow_broadcast</em>, and <em>sock</em> parameters were added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8.1: </span>The <em>reuse_address</em> parameter is no longer supported, as using <a class="reference internal" href="socket#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEADDR</span></a> poses a significant security concern for UDP. Explicitly passing <code>reuse_address=True</code> will raise an exception.</p> <p>When multiple processes with differing UIDs assign sockets to an identical UDP socket address with <code>SO_REUSEADDR</code>, incoming packets can become randomly distributed among the sockets.</p> <p>For supported platforms, <em>reuse_port</em> can be used as a replacement for similar functionality. With <em>reuse_port</em>, <a class="reference internal" href="socket#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEPORT</span></a> is used instead, which specifically prevents processes with differing UIDs from assigning sockets to the same socket address.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added support for Windows.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The <em>reuse_address</em> parameter, disabled since Python 3.9.0, 3.8.1, 3.7.6 and 3.6.10, has been entirely removed.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_unix_connection">
+<code>coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)</code> </dt> <dd>
+<p>Create a Unix connection.</p> <p>The socket family will be <a class="reference internal" href="socket#socket.AF_UNIX" title="socket.AF_UNIX"><code>AF_UNIX</code></a>; socket type will be <a class="reference internal" href="socket#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code>SOCK_STREAM</code></a>.</p> <p>A tuple of <code>(transport, protocol)</code> is returned on success.</p> <p><em>path</em> is the name of a Unix domain socket and is required, unless a <em>sock</em> parameter is specified. Abstract Unix sockets, <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, and <a class="reference internal" href="pathlib#pathlib.Path" title="pathlib.Path"><code>Path</code></a> paths are supported.</p> <p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> method for information about arguments to this method.</p> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter. The <em>path</em> parameter can now be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> </dd>
+</dl> </section> <section id="creating-network-servers"> <h3>Creating network servers</h3> <span class="target" id="loop-create-server"></span><dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_server">
+<code>coroutine loop.create_server(protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)</code> </dt> <dd>
+<p>Create a TCP server (socket type <a class="reference internal" href="socket#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code>SOCK_STREAM</code></a>) listening on <em>port</em> of the <em>host</em> address.</p> <p>Returns a <a class="reference internal" href="#asyncio.Server" title="asyncio.Server"><code>Server</code></a> object.</p> <p>Arguments:</p> <ul> <li>
+<em>protocol_factory</em> must be a callable returning a <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</li> <li>
+<p>The <em>host</em> parameter can be set to several types which determine where the server would be listening:</p> <ul class="simple"> <li>If <em>host</em> is a string, the TCP server is bound to a single network interface specified by <em>host</em>.</li> <li>If <em>host</em> is a sequence of strings, the TCP server is bound to all network interfaces specified by the sequence.</li> <li>If <em>host</em> is an empty string or <code>None</code>, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).</li> </ul> </li> <li>The <em>port</em> parameter can be set to specify which port the server should listen on. If <code>0</code> or <code>None</code> (the default), a random unused port will be selected (note that if <em>host</em> resolves to multiple network interfaces, a different random port will be selected for each interface).</li> <li>
+<em>family</em> can be set to either <a class="reference internal" href="socket#socket.AF_INET" title="socket.AF_INET"><code>socket.AF_INET</code></a> or <a class="reference internal" href="socket#socket.AF_INET6" title="socket.AF_INET6"><code>AF_INET6</code></a> to force the socket to use IPv4 or IPv6. If not set, the <em>family</em> will be determined from host name (defaults to <a class="reference internal" href="socket#socket.AF_UNSPEC" title="socket.AF_UNSPEC"><code>AF_UNSPEC</code></a>).</li> <li>
+<em>flags</em> is a bitmask for <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>getaddrinfo()</code></a>.</li> <li>
+<p><em>sock</em> can optionally be specified in order to use a preexisting socket object. If specified, <em>host</em> and <em>port</em> must not be specified.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <em>sock</em> argument transfers ownership of the socket to the server created. To close the socket, call the server’s <a class="reference internal" href="#asyncio.Server.close" title="asyncio.Server.close"><code>close()</code></a> method.</p> </div> </li> <li>
+<em>backlog</em> is the maximum number of queued connections passed to <a class="reference internal" href="socket#socket.socket.listen" title="socket.socket.listen"><code>listen()</code></a> (defaults to 100).</li> <li>
+<em>ssl</em> can be set to an <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> instance to enable TLS over the accepted connections.</li> <li>
+<em>reuse_address</em> tells the kernel to reuse a local socket in <code>TIME_WAIT</code> state, without waiting for its natural timeout to expire. If not specified will automatically be set to <code>True</code> on Unix.</li> <li>
+<em>reuse_port</em> tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows.</li> <li>
+<em>ssl_handshake_timeout</em> is (for a TLS server) the time in seconds to wait for the TLS handshake to complete before aborting the connection. <code>60.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. <code>30.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>start_serving</em> set to <code>True</code> (the default) causes the created server to start accepting connections immediately. When set to <code>False</code>, the user should await on <a class="reference internal" href="#asyncio.Server.start_serving" title="asyncio.Server.start_serving"><code>Server.start_serving()</code></a> or <a class="reference internal" href="#asyncio.Server.serve_forever" title="asyncio.Server.serve_forever"><code>Server.serve_forever()</code></a> to make the server to start accepting connections.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added support for SSL/TLS in <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.1: </span>The <em>host</em> parameter can be a sequence of strings.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>Added <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters. The socket option <a class="reference internal" href="socket#socket-unix-constants"><span class="std std-ref">socket.TCP_NODELAY</span></a> is set by default for all TCP connections.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-stream#asyncio.start_server" title="asyncio.start_server"><code>start_server()</code></a> function is a higher-level alternative API that returns a pair of <a class="reference internal" href="asyncio-stream#asyncio.StreamReader" title="asyncio.StreamReader"><code>StreamReader</code></a> and <a class="reference internal" href="asyncio-stream#asyncio.StreamWriter" title="asyncio.StreamWriter"><code>StreamWriter</code></a> that can be used in an async/await code.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.create_unix_server">
+<code>coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)</code> </dt> <dd>
+<p>Similar to <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> but works with the <a class="reference internal" href="socket#socket.AF_UNIX" title="socket.AF_UNIX"><code>AF_UNIX</code></a> socket family.</p> <p><em>path</em> is the name of a Unix domain socket, and is required, unless a <em>sock</em> argument is provided. Abstract Unix sockets, <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, and <a class="reference internal" href="pathlib#pathlib.Path" title="pathlib.Path"><code>Path</code></a> paths are supported.</p> <p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> method for information about arguments to this method.</p> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters. The <em>path</em> parameter can now be a <a class="reference internal" href="pathlib#pathlib.Path" title="pathlib.Path"><code>Path</code></a> object.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.connect_accepted_socket">
+<code>coroutine loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)</code> </dt> <dd>
+<p>Wrap an already accepted connection into a transport/protocol pair.</p> <p>This method can be used by servers that accept connections outside of asyncio but that use asyncio to handle them.</p> <p>Parameters:</p> <ul> <li>
+<em>protocol_factory</em> must be a callable returning a <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</li> <li>
+<p><em>sock</em> is a preexisting socket object returned from <a class="reference internal" href="socket#socket.socket.accept" title="socket.socket.accept"><code>socket.accept</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <em>sock</em> argument transfers ownership of the socket to the transport created. To close the socket, call the transport’s <a class="reference internal" href="asyncio-protocol#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code>close()</code></a> method.</p> </div> </li> <li>
+<em>ssl</em> can be set to an <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a> to enable SSL over the accepted connections.</li> <li>
+<em>ssl_handshake_timeout</em> is (for an SSL connection) the time in seconds to wait for the SSL handshake to complete before aborting the connection. <code>60.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. <code>30.0</code> seconds if <code>None</code> (default).</li> </ul> <p>Returns a <code>(transport, protocol)</code> pair.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.3.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> </dd>
+</dl> </section> <section id="transferring-files"> <h3>Transferring files</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sendfile">
+<code>coroutine loop.sendfile(transport, file, offset=0, count=None, *, fallback=True)</code> </dt> <dd>
+<p>Send a <em>file</em> over a <em>transport</em>. Return the total number of bytes sent.</p> <p>The method uses high-performance <a class="reference internal" href="os#os.sendfile" title="os.sendfile"><code>os.sendfile()</code></a> if available.</p> <p><em>file</em> must be a regular file object opened in binary mode.</p> <p><em>offset</em> tells from where to start reading the file. If specified, <em>count</em> is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is always updated, even when this method raises an error, and <a class="reference internal" href="io#io.IOBase.tell" title="io.IOBase.tell"><code>file.tell()</code></a> can be used to obtain the actual number of bytes sent.</p> <p><em>fallback</em> set to <code>True</code> makes asyncio to manually read and send the file when the platform does not support the sendfile system call (e.g. Windows or SSL socket on Unix).</p> <p>Raise <a class="reference internal" href="asyncio-exceptions#asyncio.SendfileNotAvailableError" title="asyncio.SendfileNotAvailableError"><code>SendfileNotAvailableError</code></a> if the system does not support the <em>sendfile</em> syscall and <em>fallback</em> is <code>False</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> </section> <section id="tls-upgrade"> <h3>TLS Upgrade</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.start_tls">
+<code>coroutine loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)</code> </dt> <dd>
+<p>Upgrade an existing transport-based connection to TLS.</p> <p>Create a TLS coder/decoder instance and insert it between the <em>transport</em> and the <em>protocol</em>. The coder/decoder implements both <em>transport</em>-facing protocol and <em>protocol</em>-facing transport.</p> <p>Return the created two-interface instance. After <em>await</em>, the <em>protocol</em> must stop using the original <em>transport</em> and communicate with the returned object only because the coder caches <em>protocol</em>-side data and sporadically exchanges extra TLS session packets with <em>transport</em>.</p> <p>In some situations (e.g. when the passed transport is already closing) this may return <code>None</code>.</p> <p>Parameters:</p> <ul class="simple"> <li>
+<em>transport</em> and <em>protocol</em> instances that methods like <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>create_server()</code></a> and <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>create_connection()</code></a> return.</li> <li>
+<em>sslcontext</em>: a configured instance of <a class="reference internal" href="ssl#ssl.SSLContext" title="ssl.SSLContext"><code>SSLContext</code></a>.</li> <li>
+<em>server_side</em> pass <code>True</code> when a server-side connection is being upgraded (like the one created by <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>create_server()</code></a>).</li> <li>
+<em>server_hostname</em>: sets or overrides the host name that the target server’s certificate will be matched against.</li> <li>
+<em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. <code>60.0</code> seconds if <code>None</code> (default).</li> <li>
+<em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown to complete before aborting the connection. <code>30.0</code> seconds if <code>None</code> (default).</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p> </div> </dd>
+</dl> </section> <section id="watching-file-descriptors"> <h3>Watching file descriptors</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.add_reader">
+<code>loop.add_reader(fd, callback, *args)</code> </dt> <dd>
+<p>Start monitoring the <em>fd</em> file descriptor for read availability and invoke <em>callback</em> with the specified arguments once <em>fd</em> is available for reading.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.remove_reader">
+<code>loop.remove_reader(fd)</code> </dt> <dd>
+<p>Stop monitoring the <em>fd</em> file descriptor for read availability. Returns <code>True</code> if <em>fd</em> was previously being monitored for reads.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.add_writer">
+<code>loop.add_writer(fd, callback, *args)</code> </dt> <dd>
+<p>Start monitoring the <em>fd</em> file descriptor for write availability and invoke <em>callback</em> with the specified arguments once <em>fd</em> is available for writing.</p> <p>Use <a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>callback</em>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.remove_writer">
+<code>loop.remove_writer(fd)</code> </dt> <dd>
+<p>Stop monitoring the <em>fd</em> file descriptor for write availability. Returns <code>True</code> if <em>fd</em> was previously being monitored for writes.</p> </dd>
+</dl> <p>See also <a class="reference internal" href="asyncio-platforms#asyncio-platform-support"><span class="std std-ref">Platform Support</span></a> section for some limitations of these methods.</p> </section> <section id="working-with-socket-objects-directly"> <h3>Working with socket objects directly</h3> <p>In general, protocol implementations that use transport-based APIs such as <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> and <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> are faster than implementations that work with sockets directly. However, there are some use cases when performance is not critical, and working with <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket</code></a> objects directly is more convenient.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_recv">
+<code>coroutine loop.sock_recv(sock, nbytes)</code> </dt> <dd>
+<p>Receive up to <em>nbytes</em> from <em>sock</em>. Asynchronous version of <a class="reference internal" href="socket#socket.socket.recv" title="socket.socket.recv"><code>socket.recv()</code></a>.</p> <p>Return the received data as a bytes object.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Even though this method was always documented as a coroutine method, releases before Python 3.7 returned a <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a>. Since Python 3.7 this is an <code>async def</code> method.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_recv_into">
+<code>coroutine loop.sock_recv_into(sock, buf)</code> </dt> <dd>
+<p>Receive data from <em>sock</em> into the <em>buf</em> buffer. Modeled after the blocking <a class="reference internal" href="socket#socket.socket.recv_into" title="socket.socket.recv_into"><code>socket.recv_into()</code></a> method.</p> <p>Return the number of bytes written to the buffer.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_recvfrom">
+<code>coroutine loop.sock_recvfrom(sock, bufsize)</code> </dt> <dd>
+<p>Receive a datagram of up to <em>bufsize</em> from <em>sock</em>. Asynchronous version of <a class="reference internal" href="socket#socket.socket.recvfrom" title="socket.socket.recvfrom"><code>socket.recvfrom()</code></a>.</p> <p>Return a tuple of (received data, remote address).</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_recvfrom_into">
+<code>coroutine loop.sock_recvfrom_into(sock, buf, nbytes=0)</code> </dt> <dd>
+<p>Receive a datagram of up to <em>nbytes</em> from <em>sock</em> into <em>buf</em>. Asynchronous version of <a class="reference internal" href="socket#socket.socket.recvfrom_into" title="socket.socket.recvfrom_into"><code>socket.recvfrom_into()</code></a>.</p> <p>Return a tuple of (number of bytes received, remote address).</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_sendall">
+<code>coroutine loop.sock_sendall(sock, data)</code> </dt> <dd>
+<p>Send <em>data</em> to the <em>sock</em> socket. Asynchronous version of <a class="reference internal" href="socket#socket.socket.sendall" title="socket.socket.sendall"><code>socket.sendall()</code></a>.</p> <p>This method continues to send to the socket until either all data in <em>data</em> has been sent or an error occurs. <code>None</code> is returned on success. On error, an exception is raised. Additionally, there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Even though the method was always documented as a coroutine method, before Python 3.7 it returned a <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a>. Since Python 3.7, this is an <code>async def</code> method.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_sendto">
+<code>coroutine loop.sock_sendto(sock, data, address)</code> </dt> <dd>
+<p>Send a datagram from <em>sock</em> to <em>address</em>. Asynchronous version of <a class="reference internal" href="socket#socket.socket.sendto" title="socket.socket.sendto"><code>socket.sendto()</code></a>.</p> <p>Return the number of bytes sent.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_connect">
+<code>coroutine loop.sock_connect(sock, address)</code> </dt> <dd>
+<p>Connect <em>sock</em> to a remote socket at <em>address</em>.</p> <p>Asynchronous version of <a class="reference internal" href="socket#socket.socket.connect" title="socket.socket.connect"><code>socket.connect()</code></a>.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.2: </span><code>address</code> no longer needs to be resolved. <code>sock_connect</code> will try to check if the <em>address</em> is already resolved by calling <a class="reference internal" href="socket#socket.inet_pton" title="socket.inet_pton"><code>socket.inet_pton()</code></a>. If not, <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code>loop.getaddrinfo()</code></a> will be used to resolve the <em>address</em>.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> and <a class="reference internal" href="asyncio-stream#asyncio.open_connection" title="asyncio.open_connection"><code>asyncio.open_connection()</code></a>.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_accept">
+<code>coroutine loop.sock_accept(sock)</code> </dt> <dd>
+<p>Accept a connection. Modeled after the blocking <a class="reference internal" href="socket#socket.socket.accept" title="socket.socket.accept"><code>socket.accept()</code></a> method.</p> <p>The socket must be bound to an address and listening for connections. The return value is a pair <code>(conn, address)</code> where <em>conn</em> is a <em>new</em> socket object usable to send and receive data on the connection, and <em>address</em> is the address bound to the socket on the other end of the connection.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Even though the method was always documented as a coroutine method, before Python 3.7 it returned a <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a>. Since Python 3.7, this is an <code>async def</code> method.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> and <a class="reference internal" href="asyncio-stream#asyncio.start_server" title="asyncio.start_server"><code>start_server()</code></a>.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.sock_sendfile">
+<code>coroutine loop.sock_sendfile(sock, file, offset=0, count=None, *, fallback=True)</code> </dt> <dd>
+<p>Send a file using high-performance <a class="reference internal" href="os#os.sendfile" title="os.sendfile"><code>os.sendfile</code></a> if possible. Return the total number of bytes sent.</p> <p>Asynchronous version of <a class="reference internal" href="socket#socket.socket.sendfile" title="socket.socket.sendfile"><code>socket.sendfile()</code></a>.</p> <p><em>sock</em> must be a non-blocking <a class="reference internal" href="socket#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code>socket.SOCK_STREAM</code></a> <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket</code></a>.</p> <p><em>file</em> must be a regular file object open in binary mode.</p> <p><em>offset</em> tells from where to start reading the file. If specified, <em>count</em> is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is always updated, even when this method raises an error, and <a class="reference internal" href="io#io.IOBase.tell" title="io.IOBase.tell"><code>file.tell()</code></a> can be used to obtain the actual number of bytes sent.</p> <p><em>fallback</em>, when set to <code>True</code>, makes asyncio manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix).</p> <p>Raise <a class="reference internal" href="asyncio-exceptions#asyncio.SendfileNotAvailableError" title="asyncio.SendfileNotAvailableError"><code>SendfileNotAvailableError</code></a> if the system does not support <em>sendfile</em> syscall and <em>fallback</em> is <code>False</code>.</p> <p><em>sock</em> must be a non-blocking socket.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> </section> <section id="dns"> <h3>DNS</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.getaddrinfo">
+<code>coroutine loop.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)</code> </dt> <dd>
+<p>Asynchronous version of <a class="reference internal" href="socket#socket.getaddrinfo" title="socket.getaddrinfo"><code>socket.getaddrinfo()</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.getnameinfo">
+<code>coroutine loop.getnameinfo(sockaddr, flags=0)</code> </dt> <dd>
+<p>Asynchronous version of <a class="reference internal" href="socket#socket.getnameinfo" title="socket.getnameinfo"><code>socket.getnameinfo()</code></a>.</p> </dd>
+</dl> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Both <em>getaddrinfo</em> and <em>getnameinfo</em> methods were always documented to return a coroutine, but prior to Python 3.7 they were, in fact, returning <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a> objects. Starting with Python 3.7 both methods are coroutines.</p> </div> </section> <section id="working-with-pipes"> <h3>Working with pipes</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.connect_read_pipe">
+<code>coroutine loop.connect_read_pipe(protocol_factory, pipe)</code> </dt> <dd>
+<p>Register the read end of <em>pipe</em> in the event loop.</p> <p><em>protocol_factory</em> must be a callable returning an <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p> <p><em>pipe</em> is a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file-like object</span></a>.</p> <p>Return pair <code>(transport, protocol)</code>, where <em>transport</em> supports the <a class="reference internal" href="asyncio-protocol#asyncio.ReadTransport" title="asyncio.ReadTransport"><code>ReadTransport</code></a> interface and <em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p> <p>With <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> event loop, the <em>pipe</em> is set to non-blocking mode.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.connect_write_pipe">
+<code>coroutine loop.connect_write_pipe(protocol_factory, pipe)</code> </dt> <dd>
+<p>Register the write end of <em>pipe</em> in the event loop.</p> <p><em>protocol_factory</em> must be a callable returning an <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p> <p><em>pipe</em> is <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file-like object</span></a>.</p> <p>Return pair <code>(transport, protocol)</code>, where <em>transport</em> supports <a class="reference internal" href="asyncio-protocol#asyncio.WriteTransport" title="asyncio.WriteTransport"><code>WriteTransport</code></a> interface and <em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p> <p>With <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> event loop, the <em>pipe</em> is set to non-blocking mode.</p> </dd>
+</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> does not support the above methods on Windows. Use <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a> instead for Windows.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>loop.subprocess_exec()</code></a> and <a class="reference internal" href="#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code>loop.subprocess_shell()</code></a> methods.</p> </div> </section> <section id="unix-signals"> <h3>Unix signals</h3> <span class="target" id="loop-add-signal-handler"></span><dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.add_signal_handler">
+<code>loop.add_signal_handler(signum, callback, *args)</code> </dt> <dd>
+<p>Set <em>callback</em> as the handler for the <em>signum</em> signal.</p> <p>The callback will be invoked by <em>loop</em>, along with other queued callbacks and runnable coroutines of that event loop. Unlike signal handlers registered using <a class="reference internal" href="signal#signal.signal" title="signal.signal"><code>signal.signal()</code></a>, a callback registered with this function is allowed to interact with the event loop.</p> <p>Raise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if the signal number is invalid or uncatchable. Raise <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> if there is a problem setting up the handler.</p> <p>Use <a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>callback</em>.</p> <p>Like <a class="reference internal" href="signal#signal.signal" title="signal.signal"><code>signal.signal()</code></a>, this function must be invoked in the main thread.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.remove_signal_handler">
+<code>loop.remove_signal_handler(sig)</code> </dt> <dd>
+<p>Remove the handler for the <em>sig</em> signal.</p> <p>Return <code>True</code> if the signal handler was removed, or <code>False</code> if no handler was set for the given signal.</p> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p> </div> </dd>
+</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="signal#module-signal" title="signal: Set handlers for asynchronous events."><code>signal</code></a> module.</p> </div> </section> <section id="executing-code-in-thread-or-process-pools"> <h3>Executing code in thread or process pools</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.run_in_executor">
+<code>awaitable loop.run_in_executor(executor, func, *args)</code> </dt> <dd>
+<p>Arrange for <em>func</em> to be called in the specified executor.</p> <p>The <em>executor</em> argument should be an <a class="reference internal" href="concurrent.futures#concurrent.futures.Executor" title="concurrent.futures.Executor"><code>concurrent.futures.Executor</code></a> instance. The default executor is used if <em>executor</em> is <code>None</code>.</p> <p>Example:</p> <pre data-language="python">import asyncio
+import concurrent.futures
+
+def blocking_io():
+ # File operations (such as logging) can block the
+ # event loop: run them in a thread pool.
+ with open('/dev/urandom', 'rb') as f:
+ return f.read(100)
+
+def cpu_bound():
+ # CPU-bound operations will block the event loop:
+ # in general it is preferable to run them in a
+ # process pool.
+ return sum(i * i for i in range(10 ** 7))
+
+async def main():
+ loop = asyncio.get_running_loop()
+
+ ## Options:
+
+ # 1. Run in the default loop's executor:
+ result = await loop.run_in_executor(
+ None, blocking_io)
+ print('default thread pool', result)
+
+ # 2. Run in a custom thread pool:
+ with concurrent.futures.ThreadPoolExecutor() as pool:
+ result = await loop.run_in_executor(
+ pool, blocking_io)
+ print('custom thread pool', result)
+
+ # 3. Run in a custom process pool:
+ with concurrent.futures.ProcessPoolExecutor() as pool:
+ result = await loop.run_in_executor(
+ pool, cpu_bound)
+ print('custom process pool', result)
+
+if __name__ == '__main__':
+ asyncio.run(main())
+</pre> <p>Note that the entry point guard (<code>if __name__ == '__main__'</code>) is required for option 3 due to the peculiarities of <a class="reference internal" href="multiprocessing#module-multiprocessing" title="multiprocessing: Process-based parallelism."><code>multiprocessing</code></a>, which is used by <a class="reference internal" href="concurrent.futures#concurrent.futures.ProcessPoolExecutor" title="concurrent.futures.ProcessPoolExecutor"><code>ProcessPoolExecutor</code></a>. See <a class="reference internal" href="multiprocessing#multiprocessing-safe-main-import"><span class="std std-ref">Safe importing of main module</span></a>.</p> <p>This method returns a <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a> object.</p> <p>Use <a class="reference internal" href="functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a> <a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to <em>func</em>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.3: </span><a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code>loop.run_in_executor()</code></a> no longer configures the <code>max_workers</code> of the thread pool executor it creates, instead leaving it up to the thread pool executor (<a class="reference internal" href="concurrent.futures#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a>) to set the default.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.set_default_executor">
+<code>loop.set_default_executor(executor)</code> </dt> <dd>
+<p>Set <em>executor</em> as the default executor used by <a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code>run_in_executor()</code></a>. <em>executor</em> must be an instance of <a class="reference internal" href="concurrent.futures#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><em>executor</em> must be an instance of <a class="reference internal" href="concurrent.futures#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code>ThreadPoolExecutor</code></a>.</p> </div> </dd>
+</dl> </section> <section id="error-handling-api"> <h3>Error Handling API</h3> <p>Allows customizing how exceptions are handled in the event loop.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.set_exception_handler">
+<code>loop.set_exception_handler(handler)</code> </dt> <dd>
+<p>Set <em>handler</em> as the new event loop exception handler.</p> <p>If <em>handler</em> is <code>None</code>, the default exception handler will be set. Otherwise, <em>handler</em> must be a callable with the signature matching <code>(loop, context)</code>, where <code>loop</code> is a reference to the active event loop, and <code>context</code> is a <code>dict</code> object containing the details of the exception (see <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code>call_exception_handler()</code></a> documentation for details about context).</p> <p>If the handler is called on behalf of a <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>Task</code></a> or <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code>Handle</code></a>, it is run in the <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> of that task or callback handle.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The handler may be called in the <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>Context</code></a> of the task or handle where the exception originated.</p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.get_exception_handler">
+<code>loop.get_exception_handler()</code> </dt> <dd>
+<p>Return the current exception handler, or <code>None</code> if no custom exception handler was set.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.default_exception_handler">
+<code>loop.default_exception_handler(context)</code> </dt> <dd>
+<p>Default exception handler.</p> <p>This is called when an exception occurs and no exception handler is set. This can be called by a custom exception handler that wants to defer to the default handler behavior.</p> <p><em>context</em> parameter has the same meaning as in <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code>call_exception_handler()</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.call_exception_handler">
+<code>loop.call_exception_handler(context)</code> </dt> <dd>
+<p>Call the current event loop exception handler.</p> <p><em>context</em> is a <code>dict</code> object containing the following keys (new keys may be introduced in future Python versions):</p> <ul class="simple"> <li>‘message’: Error message;</li> <li>‘exception’ (optional): Exception object;</li> <li>‘future’ (optional): <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>asyncio.Future</code></a> instance;</li> <li>‘task’ (optional): <a class="reference internal" href="asyncio-task#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a> instance;</li> <li>‘handle’ (optional): <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code>asyncio.Handle</code></a> instance;</li> <li>‘protocol’ (optional): <a class="reference internal" href="asyncio-protocol#asyncio-protocol"><span class="std std-ref">Protocol</span></a> instance;</li> <li>‘transport’ (optional): <a class="reference internal" href="asyncio-protocol#asyncio-transport"><span class="std std-ref">Transport</span></a> instance;</li> <li>‘socket’ (optional): <a class="reference internal" href="socket#socket.socket" title="socket.socket"><code>socket.socket</code></a> instance;</li> <li>
+<dl class="simple"> <dt>‘asyncgen’ (optional): Asynchronous generator that caused</dt>
+<dd>
+<p>the exception.</p> </dd> </dl> </li> </ul> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This method should not be overloaded in subclassed event loops. For custom exception handling, use the <a class="reference internal" href="#asyncio.loop.set_exception_handler" title="asyncio.loop.set_exception_handler"><code>set_exception_handler()</code></a> method.</p> </div> </dd>
+</dl> </section> <section id="enabling-debug-mode"> <h3>Enabling debug mode</h3> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.get_debug">
+<code>loop.get_debug()</code> </dt> <dd>
+<p>Get the debug mode (<a class="reference internal" href="functions#bool" title="bool"><code>bool</code></a>) of the event loop.</p> <p>The default value is <code>True</code> if the environment variable <span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline#envvar-PYTHONASYNCIODEBUG"><code>PYTHONASYNCIODEBUG</code></a> is set to a non-empty string, <code>False</code> otherwise.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.set_debug">
+<code>loop.set_debug(enabled: bool)</code> </dt> <dd>
+<p>Set the debug mode of the event loop.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The new <a class="reference internal" href="devmode#devmode"><span class="std std-ref">Python Development Mode</span></a> can now also be used to enable the debug mode.</p> </div> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="asyncio.loop.slow_callback_duration">
+<code>loop.slow_callback_duration</code> </dt> <dd>
+<p>This attribute can be used to set the minimum execution duration in seconds that is considered “slow”. When debug mode is enabled, “slow” callbacks are logged.</p> <p>Default value is 100 milliseconds.</p> </dd>
+</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>The <a class="reference internal" href="asyncio-dev#asyncio-debug-mode"><span class="std std-ref">debug mode of asyncio</span></a>.</p> </div> </section> <section id="running-subprocesses"> <h3>Running Subprocesses</h3> <p>Methods described in this subsections are low-level. In regular async/await code consider using the high-level <a class="reference internal" href="asyncio-subprocess#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code>asyncio.create_subprocess_shell()</code></a> and <a class="reference internal" href="asyncio-subprocess#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code>asyncio.create_subprocess_exec()</code></a> convenience functions instead.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>On Windows, the default event loop <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a> supports subprocesses, whereas <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> does not. See <a class="reference internal" href="asyncio-platforms#asyncio-windows-subprocess"><span class="std std-ref">Subprocess Support on Windows</span></a> for details.</p> </div> <span class="target" id="loop-subprocess-exec"></span><dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.subprocess_exec">
+<code>coroutine loop.subprocess_exec(protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)</code> </dt> <dd>
+<p>Create a subprocess from one or more string arguments specified by <em>args</em>.</p> <p><em>args</em> must be a list of strings represented by:</p> <ul class="simple"> <li>
+<a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>;</li> <li>or <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>, encoded to the <a class="reference internal" href="os#filesystem-encoding"><span class="std std-ref">filesystem encoding</span></a>.</li> </ul> <p>The first string specifies the program executable, and the remaining strings specify the arguments. Together, string arguments form the <code>argv</code> of the program.</p> <p>This is similar to the standard library <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>subprocess.Popen</code></a> class called with <code>shell=False</code> and the list of strings passed as the first argument; however, where <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>Popen</code></a> takes a single argument which is list of strings, <em>subprocess_exec</em> takes multiple string arguments.</p> <p>The <em>protocol_factory</em> must be a callable returning a subclass of the <a class="reference internal" href="asyncio-protocol#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code>asyncio.SubprocessProtocol</code></a> class.</p> <p>Other parameters:</p> <ul> <li>
+<p><em>stdin</em> can be any of these:</p> <ul class="simple"> <li>a file-like object</li> <li>an existing file descriptor (a positive integer), for example those created with <a class="reference internal" href="os#os.pipe" title="os.pipe"><code>os.pipe()</code></a>
+</li> <li>the <a class="reference internal" href="subprocess#subprocess.PIPE" title="subprocess.PIPE"><code>subprocess.PIPE</code></a> constant (default) which will create a new pipe and connect it,</li> <li>the value <code>None</code> which will make the subprocess inherit the file descriptor from this process</li> <li>the <a class="reference internal" href="subprocess#subprocess.DEVNULL" title="subprocess.DEVNULL"><code>subprocess.DEVNULL</code></a> constant which indicates that the special <a class="reference internal" href="os#os.devnull" title="os.devnull"><code>os.devnull</code></a> file will be used</li> </ul> </li> <li>
+<p><em>stdout</em> can be any of these:</p> <ul class="simple"> <li>a file-like object</li> <li>the <a class="reference internal" href="subprocess#subprocess.PIPE" title="subprocess.PIPE"><code>subprocess.PIPE</code></a> constant (default) which will create a new pipe and connect it,</li> <li>the value <code>None</code> which will make the subprocess inherit the file descriptor from this process</li> <li>the <a class="reference internal" href="subprocess#subprocess.DEVNULL" title="subprocess.DEVNULL"><code>subprocess.DEVNULL</code></a> constant which indicates that the special <a class="reference internal" href="os#os.devnull" title="os.devnull"><code>os.devnull</code></a> file will be used</li> </ul> </li> <li>
+<p><em>stderr</em> can be any of these:</p> <ul class="simple"> <li>a file-like object</li> <li>the <a class="reference internal" href="subprocess#subprocess.PIPE" title="subprocess.PIPE"><code>subprocess.PIPE</code></a> constant (default) which will create a new pipe and connect it,</li> <li>the value <code>None</code> which will make the subprocess inherit the file descriptor from this process</li> <li>the <a class="reference internal" href="subprocess#subprocess.DEVNULL" title="subprocess.DEVNULL"><code>subprocess.DEVNULL</code></a> constant which indicates that the special <a class="reference internal" href="os#os.devnull" title="os.devnull"><code>os.devnull</code></a> file will be used</li> <li>the <a class="reference internal" href="subprocess#subprocess.STDOUT" title="subprocess.STDOUT"><code>subprocess.STDOUT</code></a> constant which will connect the standard error stream to the process’ standard output stream</li> </ul> </li> <li>
+<p>All other keyword arguments are passed to <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>subprocess.Popen</code></a> without interpretation, except for <em>bufsize</em>, <em>universal_newlines</em>, <em>shell</em>, <em>text</em>, <em>encoding</em> and <em>errors</em>, which should not be specified at all.</p> <p>The <code>asyncio</code> subprocess API does not support decoding the streams as text. <a class="reference internal" href="stdtypes#bytes.decode" title="bytes.decode"><code>bytes.decode()</code></a> can be used to convert the bytes returned from the stream to text.</p> </li> </ul> <p>If a file-like object passed as <em>stdin</em>, <em>stdout</em> or <em>stderr</em> represents a pipe, then the other side of this pipe should be registered with <a class="reference internal" href="#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code>connect_write_pipe()</code></a> or <a class="reference internal" href="#asyncio.loop.connect_read_pipe" title="asyncio.loop.connect_read_pipe"><code>connect_read_pipe()</code></a> for use with the event loop.</p> <p>See the constructor of the <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>subprocess.Popen</code></a> class for documentation on other arguments.</p> <p>Returns a pair of <code>(transport, protocol)</code>, where <em>transport</em> conforms to the <a class="reference internal" href="asyncio-protocol#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code>asyncio.SubprocessTransport</code></a> base class and <em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.loop.subprocess_shell">
+<code>coroutine loop.subprocess_shell(protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)</code> </dt> <dd>
+<p>Create a subprocess from <em>cmd</em>, which can be a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> or a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> string encoded to the <a class="reference internal" href="os#filesystem-encoding"><span class="std std-ref">filesystem encoding</span></a>, using the platform’s “shell” syntax.</p> <p>This is similar to the standard library <a class="reference internal" href="subprocess#subprocess.Popen" title="subprocess.Popen"><code>subprocess.Popen</code></a> class called with <code>shell=True</code>.</p> <p>The <em>protocol_factory</em> must be a callable returning a subclass of the <a class="reference internal" href="asyncio-protocol#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code>SubprocessProtocol</code></a> class.</p> <p>See <a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code>subprocess_exec()</code></a> for more details about the remaining arguments.</p> <p>Returns a pair of <code>(transport, protocol)</code>, where <em>transport</em> conforms to the <a class="reference internal" href="asyncio-protocol#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code>SubprocessTransport</code></a> base class and <em>protocol</em> is an object instantiated by the <em>protocol_factory</em>.</p> </dd>
+</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p>It is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid <a class="reference external" href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection">shell injection</a> vulnerabilities. The <a class="reference internal" href="shlex#shlex.quote" title="shlex.quote"><code>shlex.quote()</code></a> function can be used to properly escape whitespace and special characters in strings that are going to be used to construct shell commands.</p> </div> </section> </section> <section id="callback-handles"> <h2>Callback Handles</h2> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Handle">
+<code>class asyncio.Handle</code> </dt> <dd>
+<p>A callback wrapper object returned by <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a>, <a class="reference internal" href="#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code>loop.call_soon_threadsafe()</code></a>.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Handle.get_context">
+<code>get_context()</code> </dt> <dd>
+<p>Return the <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> object associated with the handle.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Handle.cancel">
+<code>cancel()</code> </dt> <dd>
+<p>Cancel the callback. If the callback has already been canceled or executed, this method has no effect.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Handle.cancelled">
+<code>cancelled()</code> </dt> <dd>
+<p>Return <code>True</code> if the callback was cancelled.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.TimerHandle">
+<code>class asyncio.TimerHandle</code> </dt> <dd>
+<p>A callback wrapper object returned by <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code>loop.call_later()</code></a>, and <a class="reference internal" href="#asyncio.loop.call_at" title="asyncio.loop.call_at"><code>loop.call_at()</code></a>.</p> <p>This class is a subclass of <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code>Handle</code></a>.</p> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.TimerHandle.when">
+<code>when()</code> </dt> <dd>
+<p>Return a scheduled callback time as <a class="reference internal" href="functions#float" title="float"><code>float</code></a> seconds.</p> <p>The time is an absolute timestamp, using the same time reference as <a class="reference internal" href="#asyncio.loop.time" title="asyncio.loop.time"><code>loop.time()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> </dd>
+</dl> </section> <section id="server-objects"> <h2>Server Objects</h2> <p>Server objects are created by <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a>, <a class="reference internal" href="#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code>loop.create_unix_server()</code></a>, <a class="reference internal" href="asyncio-stream#asyncio.start_server" title="asyncio.start_server"><code>start_server()</code></a>, and <a class="reference internal" href="asyncio-stream#asyncio.start_unix_server" title="asyncio.start_unix_server"><code>start_unix_server()</code></a> functions.</p> <p>Do not instantiate the <a class="reference internal" href="#asyncio.Server" title="asyncio.Server"><code>Server</code></a> class directly.</p> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Server">
+<code>class asyncio.Server</code> </dt> <dd>
+<p><em>Server</em> objects are asynchronous context managers. When used in an <code>async with</code> statement, it’s guaranteed that the Server object is closed and not accepting new connections when the <code>async with</code> statement is completed:</p> <pre data-language="python">srv = await loop.create_server(...)
+
+async with srv:
+ # some code
+
+# At this point, srv is closed and no longer accepts new connections.
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Server object is an asynchronous context manager since Python 3.7.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>This class was exposed publicly as <code>asyncio.Server</code> in Python 3.9.11, 3.10.3 and 3.11.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.close">
+<code>close()</code> </dt> <dd>
+<p>Stop serving: close listening sockets and set the <a class="reference internal" href="#asyncio.Server.sockets" title="asyncio.Server.sockets"><code>sockets</code></a> attribute to <code>None</code>.</p> <p>The sockets that represent existing incoming client connections are left open.</p> <p>The server is closed asynchronously; use the <a class="reference internal" href="#asyncio.Server.wait_closed" title="asyncio.Server.wait_closed"><code>wait_closed()</code></a> coroutine to wait until the server is closed (and no more connections are active).</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.get_loop">
+<code>get_loop()</code> </dt> <dd>
+<p>Return the event loop associated with the server object.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.start_serving">
+<code>coroutine start_serving()</code> </dt> <dd>
+<p>Start accepting connections.</p> <p>This method is idempotent, so it can be called when the server is already serving.</p> <p>The <em>start_serving</em> keyword-only parameter to <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code>loop.create_server()</code></a> and <a class="reference internal" href="asyncio-stream#asyncio.start_server" title="asyncio.start_server"><code>asyncio.start_server()</code></a> allows creating a Server object that is not accepting connections initially. In this case <code>Server.start_serving()</code>, or <a class="reference internal" href="#asyncio.Server.serve_forever" title="asyncio.Server.serve_forever"><code>Server.serve_forever()</code></a> can be used to make the Server start accepting connections.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.serve_forever">
+<code>coroutine serve_forever()</code> </dt> <dd>
+<p>Start accepting connections until the coroutine is cancelled. Cancellation of <code>serve_forever</code> task causes the server to be closed.</p> <p>This method can be called if the server is already accepting connections. Only one <code>serve_forever</code> task can exist per one <em>Server</em> object.</p> <p>Example:</p> <pre data-language="python">async def client_connected(reader, writer):
+ # Communicate with the client with
+ # reader/writer streams. For example:
+ await reader.readline()
+
+async def main(host, port):
+ srv = await asyncio.start_server(
+ client_connected, host, port)
+ await srv.serve_forever()
+
+asyncio.run(main('127.0.0.1', 0))
+</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.is_serving">
+<code>is_serving()</code> </dt> <dd>
+<p>Return <code>True</code> if the server is accepting new connections.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Server.wait_closed">
+<code>coroutine wait_closed()</code> </dt> <dd>
+<p>Wait until the <a class="reference internal" href="#asyncio.Server.close" title="asyncio.Server.close"><code>close()</code></a> method completes and all active connections have finished.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="asyncio.Server.sockets">
+<code>sockets</code> </dt> <dd>
+<p>List of socket-like objects, <code>asyncio.trsock.TransportSocket</code>, which the server is listening on.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Prior to Python 3.7 <code>Server.sockets</code> used to return an internal list of server sockets directly. In 3.7 a copy of that list is returned.</p> </div> </dd>
+</dl> </dd>
+</dl> </section> <section id="event-loop-implementations"> <span id="asyncio-event-loop-implementations"></span><span id="asyncio-event-loops"></span><h2>Event Loop Implementations</h2> <p>asyncio ships with two different event loop implementations: <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a>.</p> <p>By default asyncio is configured to use <a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code>SelectorEventLoop</code></a> on Unix and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code>ProactorEventLoop</code></a> on Windows.</p> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.SelectorEventLoop">
+<code>class asyncio.SelectorEventLoop</code> </dt> <dd>
+<p>An event loop based on the <a class="reference internal" href="selectors#module-selectors" title="selectors: High-level I/O multiplexing."><code>selectors</code></a> module.</p> <p>Uses the most efficient <em>selector</em> available for the given platform. It is also possible to manually configure the exact selector implementation to be used:</p> <pre data-language="python">import asyncio
+import selectors
+
+class MyPolicy(asyncio.DefaultEventLoopPolicy):
+ def new_event_loop(self):
+ selector = selectors.SelectSelector()
+ return asyncio.SelectorEventLoop(selector)
+
+asyncio.set_event_loop_policy(MyPolicy())
+</pre> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix, Windows.</p> </div> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.ProactorEventLoop">
+<code>class asyncio.ProactorEventLoop</code> </dt> <dd>
+<p>An event loop for Windows that uses “I/O Completion Ports” (IOCP).</p> <div class="availability docutils container"> <p><a class="reference internal" href="https://docs.python.org/3.12/library/intro.html#availability"><span class="std std-ref">Availability</span></a>: Windows.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference external" href="https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports">MSDN documentation on I/O Completion Ports</a>.</p> </div> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.AbstractEventLoop">
+<code>class asyncio.AbstractEventLoop</code> </dt> <dd>
+<p>Abstract base class for asyncio-compliant event loops.</p> <p>The <a class="reference internal" href="#asyncio-event-loop-methods"><span class="std std-ref">Event Loop Methods</span></a> section lists all methods that an alternative implementation of <code>AbstractEventLoop</code> should have defined.</p> </dd>
+</dl> </section> <section id="examples"> <h2>Examples</h2> <p>Note that all examples in this section <strong>purposefully</strong> show how to use the low-level event loop APIs, such as <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code>loop.run_forever()</code></a> and <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a>. Modern asyncio applications rarely need to be written this way; consider using the high-level functions like <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a>.</p> <section id="hello-world-with-call-soon"> <span id="asyncio-example-lowlevel-helloworld"></span><h3>Hello World with call_soon()</h3> <p>An example using the <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code>loop.call_soon()</code></a> method to schedule a callback. The callback displays <code>"Hello World"</code> and then stops the event loop:</p> <pre data-language="python">import asyncio
+
+def hello_world(loop):
+ """A callback to print 'Hello World' and stop the event loop"""
+ print('Hello World')
+ loop.stop()
+
+loop = asyncio.new_event_loop()
+
+# Schedule a call to hello_world()
+loop.call_soon(hello_world, loop)
+
+# Blocking call interrupted by loop.stop()
+try:
+ loop.run_forever()
+finally:
+ loop.close()
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>A similar <a class="reference internal" href="asyncio-task#coroutine"><span class="std std-ref">Hello World</span></a> example created with a coroutine and the <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>run()</code></a> function.</p> </div> </section> <section id="display-the-current-date-with-call-later"> <span id="asyncio-example-call-later"></span><h3>Display the current date with call_later()</h3> <p>An example of a callback displaying the current date every second. The callback uses the <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code>loop.call_later()</code></a> method to reschedule itself after 5 seconds, and then stops the event loop:</p> <pre data-language="python">import asyncio
+import datetime
+
+def display_date(end_time, loop):
+ print(datetime.datetime.now())
+ if (loop.time() + 1.0) &lt; end_time:
+ loop.call_later(1, display_date, end_time, loop)
+ else:
+ loop.stop()
+
+loop = asyncio.new_event_loop()
+
+# Schedule the first call to display_date()
+end_time = loop.time() + 5.0
+loop.call_soon(display_date, end_time, loop)
+
+# Blocking call interrupted by loop.stop()
+try:
+ loop.run_forever()
+finally:
+ loop.close()
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>A similar <a class="reference internal" href="asyncio-task#asyncio-example-sleep"><span class="std std-ref">current date</span></a> example created with a coroutine and the <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>run()</code></a> function.</p> </div> </section> <section id="watch-a-file-descriptor-for-read-events"> <span id="asyncio-example-watch-fd"></span><h3>Watch a file descriptor for read events</h3> <p>Wait until a file descriptor received some data using the <a class="reference internal" href="#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code>loop.add_reader()</code></a> method and then close the event loop:</p> <pre data-language="python">import asyncio
+from socket import socketpair
+
+# Create a pair of connected file descriptors
+rsock, wsock = socketpair()
+
+loop = asyncio.new_event_loop()
+
+def reader():
+ data = rsock.recv(100)
+ print("Received:", data.decode())
+
+ # We are done: unregister the file descriptor
+ loop.remove_reader(rsock)
+
+ # Stop the event loop
+ loop.stop()
+
+# Register the file descriptor for read event
+loop.add_reader(rsock, reader)
+
+# Simulate the reception of data from the network
+loop.call_soon(wsock.send, 'abc'.encode())
+
+try:
+ # Run the event loop
+ loop.run_forever()
+finally:
+ # We are done. Close sockets and the event loop.
+ rsock.close()
+ wsock.close()
+ loop.close()
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <ul class="simple"> <li>A similar <a class="reference internal" href="asyncio-protocol#asyncio-example-create-connection"><span class="std std-ref">example</span></a> using transports, protocols, and the <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code>loop.create_connection()</code></a> method.</li> <li>Another similar <a class="reference internal" href="asyncio-stream#asyncio-example-create-connection-streams"><span class="std std-ref">example</span></a> using the high-level <a class="reference internal" href="asyncio-stream#asyncio.open_connection" title="asyncio.open_connection"><code>asyncio.open_connection()</code></a> function and streams.</li> </ul> </div> </section> <section id="set-signal-handlers-for-sigint-and-sigterm"> <span id="asyncio-example-unix-signals"></span><h3>Set signal handlers for SIGINT and SIGTERM</h3> <p>(This <code>signals</code> example only works on Unix.)</p> <p>Register handlers for signals <a class="reference internal" href="signal#signal.SIGINT" title="signal.SIGINT"><code>SIGINT</code></a> and <a class="reference internal" href="signal#signal.SIGTERM" title="signal.SIGTERM"><code>SIGTERM</code></a> using the <a class="reference internal" href="#asyncio.loop.add_signal_handler" title="asyncio.loop.add_signal_handler"><code>loop.add_signal_handler()</code></a> method:</p> <pre data-language="python">import asyncio
+import functools
+import os
+import signal
+
+def ask_exit(signame, loop):
+ print("got signal %s: exit" % signame)
+ loop.stop()
+
+async def main():
+ loop = asyncio.get_running_loop()
+
+ for signame in {'SIGINT', 'SIGTERM'}:
+ loop.add_signal_handler(
+ getattr(signal, signame),
+ functools.partial(ask_exit, signame, loop))
+
+ await asyncio.sleep(3600)
+
+print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
+print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
+
+asyncio.run(main())
+</pre> </section> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/asyncio-eventloop.html" class="_attribution-link">https://docs.python.org/3.12/library/asyncio-eventloop.html</a>
+ </p>
+</div>