Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
asyncio-eventloop.html2374 linesDownload Raw Back to docs
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4  <head>5    <meta charset="utf-8" />6    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="Event Loop" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/asyncio-eventloop.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/asyncio/events.py, Lib/asyncio/base_events.py Preface The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO ..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_asyncio-eventloop_1be14a63.png" />15<meta property="og:image:alt" content="Source code: Lib/asyncio/events.py, Lib/asyncio/base_events.py Preface The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO ..." />16<meta name="description" content="Source code: Lib/asyncio/events.py, Lib/asyncio/base_events.py Preface The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO ..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>Event Loop &#8212; Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21    22    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23    <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25    <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27    28    <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29    <script src="../_static/doctools.js?v=9bcbadda"></script>30    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31    <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32    33    <script src="../_static/sidebar.js"></script>34    35    <link rel="search" type="application/opensearchdescription+xml"36          title="Search within Python 3.15.0a6 documentation"37          href="../_static/opensearch.xml"/>38    <link rel="author" title="About these documents" href="../about.html" />39    <link rel="index" title="Index" href="../genindex.html" />40    <link rel="search" title="Search" href="../search.html" />41    <link rel="copyright" title="Copyright" href="../copyright.html" />42    <link rel="next" title="Futures" href="asyncio-future.html" />43    <link rel="prev" title="Call Graph Introspection" href="asyncio-graph.html" />44    45      46      <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47      48      <link rel="canonical" href="https://docs.python.org/3/library/asyncio-eventloop.html">49      50    51 52    53    <style>54      @media only screen {55        table.full-width-table {56            width: 100%;57        }58      }59    </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61    <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62            <script type="text/javascript" src="../_static/copybutton.js"></script>63            <script type="text/javascript" src="../_static/menu.js"></script>64            <script type="text/javascript" src="../_static/search-focus.js"></script>65            <script type="text/javascript" src="../_static/themetoggle.js"></script> 66            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67            <meta name="readthedocs-addons-api-version" content="1">68 69  </head>70<body>71<div class="mobile-nav">72    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74    <nav class="nav-content" role="navigation">75        <label for="menuToggler" class="toggler__label">76            <span></span>77        </label>78        <span class="nav-items-wrapper">79            <a href="https://www.python.org/" class="nav-logo">80                <img src="../_static/py.svg" alt="Python logo">81            </a>82            <span class="version_switcher_placeholder"></span>83            <form role="search" class="search" action="../search.html" method="get">84                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86                </svg>87                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88                <input type="submit" value="Go">89            </form>90        </span>91    </nav>92    <div class="menu-wrapper">93        <nav class="menu" role="navigation" aria-label="main navigation">94            <div class="language_switcher_placeholder"></div>95            96<label class="theme-selector-label">97    Theme98    <select class="theme-selector" oninput="activateTheme(this.value)">99        <option value="auto" selected>Auto</option>100        <option value="light">Light</option>101        <option value="dark">Dark</option>102    </select>103</label>104  <div>105    <h3><a href="../contents.html">Table of Contents</a></h3>106    <ul>107<li><a class="reference internal" href="#">Event Loop</a><ul>108<li><a class="reference internal" href="#event-loop-methods">Event Loop Methods</a><ul>109<li><a class="reference internal" href="#running-and-stopping-the-loop">Running and stopping the loop</a></li>110<li><a class="reference internal" href="#scheduling-callbacks">Scheduling callbacks</a></li>111<li><a class="reference internal" href="#scheduling-delayed-callbacks">Scheduling delayed callbacks</a></li>112<li><a class="reference internal" href="#creating-futures-and-tasks">Creating Futures and Tasks</a></li>113<li><a class="reference internal" href="#opening-network-connections">Opening network connections</a></li>114<li><a class="reference internal" href="#creating-network-servers">Creating network servers</a></li>115<li><a class="reference internal" href="#transferring-files">Transferring files</a></li>116<li><a class="reference internal" href="#tls-upgrade">TLS Upgrade</a></li>117<li><a class="reference internal" href="#watching-file-descriptors">Watching file descriptors</a></li>118<li><a class="reference internal" href="#working-with-socket-objects-directly">Working with socket objects directly</a></li>119<li><a class="reference internal" href="#dns">DNS</a></li>120<li><a class="reference internal" href="#working-with-pipes">Working with pipes</a></li>121<li><a class="reference internal" href="#unix-signals">Unix signals</a></li>122<li><a class="reference internal" href="#executing-code-in-thread-or-process-pools">Executing code in thread or process pools</a></li>123<li><a class="reference internal" href="#error-handling-api">Error Handling API</a></li>124<li><a class="reference internal" href="#enabling-debug-mode">Enabling debug mode</a></li>125<li><a class="reference internal" href="#running-subprocesses">Running Subprocesses</a></li>126</ul>127</li>128<li><a class="reference internal" href="#callback-handles">Callback Handles</a></li>129<li><a class="reference internal" href="#server-objects">Server Objects</a></li>130<li><a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a></li>131<li><a class="reference internal" href="#examples">Examples</a><ul>132<li><a class="reference internal" href="#hello-world-with-call-soon">Hello World with call_soon()</a></li>133<li><a class="reference internal" href="#display-the-current-date-with-call-later">Display the current date with call_later()</a></li>134<li><a class="reference internal" href="#watch-a-file-descriptor-for-read-events">Watch a file descriptor for read events</a></li>135<li><a class="reference internal" href="#set-signal-handlers-for-sigint-and-sigterm">Set signal handlers for SIGINT and SIGTERM</a></li>136</ul>137</li>138</ul>139</li>140</ul>141 142  </div>143  <div>144    <h4>Previous topic</h4>145    <p class="topless"><a href="asyncio-graph.html"146                          title="previous chapter">Call Graph Introspection</a></p>147  </div>148  <div>149    <h4>Next topic</h4>150    <p class="topless"><a href="asyncio-future.html"151                          title="next chapter">Futures</a></p>152  </div>153  <script>154    document.addEventListener('DOMContentLoaded', () => {155        const title = document.querySelector('meta[property="og:title"]').content;156        const elements = document.querySelectorAll('.improvepage');157        const pageurl = window.location.href.split('?')[0];158        elements.forEach(element => {159            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));160            url.searchParams.set('pagetitle', title);161            url.searchParams.set('pageurl', pageurl);162            url.searchParams.set('pagesource', "library/asyncio-eventloop.rst");163            element.href = url.toString();164        });165    });166  </script>167  <div role="note" aria-label="source link">168    <h3>This page</h3>169    <ul class="this-page-menu">170      <li><a href="../bugs.html">Report a bug</a></li>171      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>172      <li>173        <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-eventloop.rst?plain=1"174            rel="nofollow">Show source175        </a>176      </li>177      178    </ul>179  </div>180        </nav>181    </div>182</div>183 184  185    <div class="related" role="navigation" aria-label="Related">186      <h3>Navigation</h3>187      <ul>188        <li class="right" style="margin-right: 10px">189          <a href="../genindex.html" title="General Index"190             accesskey="I">index</a></li>191        <li class="right" >192          <a href="../py-modindex.html" title="Python Module Index"193             >modules</a> |</li>194        <li class="right" >195          <a href="asyncio-future.html" title="Futures"196             accesskey="N">next</a> |</li>197        <li class="right" >198          <a href="asyncio-graph.html" title="Call Graph Introspection"199             accesskey="P">previous</a> |</li>200 201          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>202          <li><a href="https://www.python.org/">Python</a> &#187;</li>203          <li class="switchers">204            <div class="language_switcher_placeholder"></div>205            <div class="version_switcher_placeholder"></div>206          </li>207          <li>208              209          </li>210    <li id="cpython-language-and-version">211      <a href="../index.html">3.15.0a6 Documentation</a> &#187;212    </li>213 214          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>215          <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>216          <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>217        <li class="nav-item nav-item-this"><a href="">Event Loop</a></li>218                <li class="right">219                    220 221    <div class="inline-search" role="search">222        <form class="inline-search" action="../search.html" method="get">223          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">224          <input type="submit" value="Go">225        </form>226    </div>227                     |228                </li>229            <li class="right">230<label class="theme-selector-label">231    Theme232    <select class="theme-selector" oninput="activateTheme(this.value)">233        <option value="auto" selected>Auto</option>234        <option value="light">Light</option>235        <option value="dark">Dark</option>236    </select>237</label> |</li>238            239      </ul>240    </div>    241 242    <div class="document">243      <div class="documentwrapper">244        <div class="bodywrapper">245          <div class="body" role="main">246            247  <section id="event-loop">248<span id="asyncio-event-loop"></span><h1>Event Loop<a class="headerlink" href="#event-loop" title="Link to this heading">¶</a></h1>249<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/events.py">Lib/asyncio/events.py</a>,250<a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a></p>251<hr class="docutils" />252<p class="rubric">Preface</p>253<p>The event loop is the core of every asyncio application.254Event loops run asynchronous tasks and callbacks, perform network255IO operations, and run subprocesses.</p>256<p>Application developers should typically use the high-level asyncio functions,257such as <a class="reference internal" href="asyncio-runner.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a>, and should rarely need to reference the loop258object or call its methods.  This section is intended mostly for authors259of lower-level code, libraries, and frameworks, who need finer control over260the event loop behavior.</p>261<p class="rubric">Obtaining the Event Loop</p>262<p>The following low-level functions can be used to get, set, or create263an event loop:</p>264<dl class="py function">265<dt class="sig sig-object py" id="asyncio.get_running_loop">266<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">get_running_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_running_loop" title="Link to this definition">¶</a></dt>267<dd><p>Return the running event loop in the current OS thread.</p>268<p>Raise a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if there is no running event loop.</p>269<p>This function can only be called from a coroutine or a callback.</p>270<div class="versionadded">271<p><span class="versionmodified added">Added in version 3.7.</span></p>272</div>273</dd></dl>274 275<dl class="py function">276<dt class="sig sig-object py" id="asyncio.get_event_loop">277<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">get_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_event_loop" title="Link to this definition">¶</a></dt>278<dd><p>Get the current event loop.</p>279<p>When called from a coroutine or a callback (e.g. scheduled with280call_soon or similar API), this function will always return the281running event loop.</p>282<p>If there is no running event loop set, the function will return283the result of the <code class="docutils literal notranslate"><span class="pre">get_event_loop_policy().get_event_loop()</span></code> call.</p>284<p>Because this function has rather complex behavior (especially285when custom event loop policies are in use), using the286<a class="reference internal" href="#asyncio.get_running_loop" title="asyncio.get_running_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_running_loop()</span></code></a> function is preferred to <code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code>287in coroutines and callbacks.</p>288<p>As noted above, consider using the higher-level <a class="reference internal" href="asyncio-runner.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> function,289instead of using these lower level functions to manually create and close an290event loop.</p>291<div class="versionchanged">292<p><span class="versionmodified changed">Changed in version 3.14: </span>Raises a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if there is no current event loop.</p>293</div>294<div class="admonition note">295<p class="admonition-title">Note</p>296<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> policy system is deprecated and will be removed297in Python 3.16; from there on, this function will return the current298running event loop if present else it will return the299loop set by <a class="reference internal" href="#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop()</span></code></a>.</p>300</div>301</dd></dl>302 303<dl class="py function">304<dt class="sig sig-object py" id="asyncio.set_event_loop">305<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">set_event_loop</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">loop</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.set_event_loop" title="Link to this definition">¶</a></dt>306<dd><p>Set <em>loop</em> as the current event loop for the current OS thread.</p>307</dd></dl>308 309<dl class="py function">310<dt class="sig sig-object py" id="asyncio.new_event_loop">311<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">new_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.new_event_loop" title="Link to this definition">¶</a></dt>312<dd><p>Create and return a new event loop object.</p>313</dd></dl>314 315<p>Note that the behaviour of <a class="reference internal" href="#asyncio.get_event_loop" title="asyncio.get_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_event_loop()</span></code></a>, <a class="reference internal" href="#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_event_loop()</span></code></a>,316and <a class="reference internal" href="#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">new_event_loop()</span></code></a> functions can be altered by317<a class="reference internal" href="asyncio-policy.html#asyncio-policies"><span class="std std-ref">setting a custom event loop policy</span></a>.</p>318<p class="rubric">Contents</p>319<p>This documentation page contains the following sections:</p>320<ul class="simple">321<li><p>The <a class="reference internal" href="#event-loop-methods">Event Loop Methods</a> section is the reference documentation of322the event loop APIs;</p></li>323<li><p>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 class="xref py py-class docutils literal notranslate"><span class="pre">Handle</span></code></a> and324<a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimerHandle</span></code></a> instances which are returned from scheduling325methods such as <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_soon()</span></code></a> and <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code></a>;</p></li>326<li><p>The <a class="reference internal" href="#server-objects">Server Objects</a> section documents types returned from327event loop methods like <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>;</p></li>328<li><p>The <a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a> section documents the329<a class="reference internal" href="#asyncio.SelectorEventLoop" title="asyncio.SelectorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">SelectorEventLoop</span></code></a> and <a class="reference internal" href="#asyncio.ProactorEventLoop" title="asyncio.ProactorEventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a> classes;</p></li>330<li><p>The <a class="reference internal" href="#examples">Examples</a> section showcases how to work with some event331loop APIs.</p></li>332</ul>333<section id="event-loop-methods">334<span id="asyncio-event-loop-methods"></span><h2>Event Loop Methods<a class="headerlink" href="#event-loop-methods" title="Link to this heading">¶</a></h2>335<p>Event loops have <strong>low-level</strong> APIs for the following:</p>336<nav class="contents local" id="contents">337<ul class="simple">338<li><p><a class="reference internal" href="#running-and-stopping-the-loop" id="id1">Running and stopping the loop</a></p></li>339<li><p><a class="reference internal" href="#scheduling-callbacks" id="id2">Scheduling callbacks</a></p></li>340<li><p><a class="reference internal" href="#scheduling-delayed-callbacks" id="id3">Scheduling delayed callbacks</a></p></li>341<li><p><a class="reference internal" href="#creating-futures-and-tasks" id="id4">Creating Futures and Tasks</a></p></li>342<li><p><a class="reference internal" href="#opening-network-connections" id="id5">Opening network connections</a></p></li>343<li><p><a class="reference internal" href="#creating-network-servers" id="id6">Creating network servers</a></p></li>344<li><p><a class="reference internal" href="#transferring-files" id="id7">Transferring files</a></p></li>345<li><p><a class="reference internal" href="#tls-upgrade" id="id8">TLS Upgrade</a></p></li>346<li><p><a class="reference internal" href="#watching-file-descriptors" id="id9">Watching file descriptors</a></p></li>347<li><p><a class="reference internal" href="#working-with-socket-objects-directly" id="id10">Working with socket objects directly</a></p></li>348<li><p><a class="reference internal" href="#dns" id="id11">DNS</a></p></li>349<li><p><a class="reference internal" href="#working-with-pipes" id="id12">Working with pipes</a></p></li>350<li><p><a class="reference internal" href="#unix-signals" id="id13">Unix signals</a></p></li>351<li><p><a class="reference internal" href="#executing-code-in-thread-or-process-pools" id="id14">Executing code in thread or process pools</a></p></li>352<li><p><a class="reference internal" href="#error-handling-api" id="id15">Error Handling API</a></p></li>353<li><p><a class="reference internal" href="#enabling-debug-mode" id="id16">Enabling debug mode</a></p></li>354<li><p><a class="reference internal" href="#running-subprocesses" id="id17">Running Subprocesses</a></p></li>355</ul>356</nav>357<section id="running-and-stopping-the-loop">358<h3><a class="toc-backref" href="#id1" role="doc-backlink">Running and stopping the loop</a><a class="headerlink" href="#running-and-stopping-the-loop" title="Link to this heading">¶</a></h3>359<dl class="py method">360<dt class="sig sig-object py" id="asyncio.loop.run_until_complete">361<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">run_until_complete</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">future</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_until_complete" title="Link to this definition">¶</a></dt>362<dd><p>Run until the <em>future</em> (an instance of <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>) has363completed.</p>364<p>If the argument is a <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">coroutine object</span></a> it365is implicitly scheduled to run as a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>.</p>366<p>Return the Future’s result or raise its exception.</p>367</dd></dl>368 369<dl class="py method">370<dt class="sig sig-object py" id="asyncio.loop.run_forever">371<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">run_forever</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_forever" title="Link to this definition">¶</a></dt>372<dd><p>Run the event loop until <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called.</p>373<p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called before <code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code> is called,374the loop will poll the I/O selector once with a timeout of zero,375run all callbacks scheduled in response to I/O events (and376those that were already scheduled), and then exit.</p>377<p>If <a class="reference internal" href="#asyncio.loop.stop" title="asyncio.loop.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> is called while <code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code> is running,378the loop will run the current batch of callbacks and then exit.379Note that new callbacks scheduled by callbacks will not run in this380case; instead, they will run the next time <code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code> or381<a class="reference internal" href="#asyncio.loop.run_until_complete" title="asyncio.loop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> is called.</p>382</dd></dl>383 384<dl class="py method">385<dt class="sig sig-object py" id="asyncio.loop.stop">386<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">stop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.stop" title="Link to this definition">¶</a></dt>387<dd><p>Stop the event loop.</p>388</dd></dl>389 390<dl class="py method">391<dt class="sig sig-object py" id="asyncio.loop.is_running">392<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">is_running</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_running" title="Link to this definition">¶</a></dt>393<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event loop is currently running.</p>394</dd></dl>395 396<dl class="py method">397<dt class="sig sig-object py" id="asyncio.loop.is_closed">398<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">is_closed</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_closed" title="Link to this definition">¶</a></dt>399<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the event loop was closed.</p>400</dd></dl>401 402<dl class="py method">403<dt class="sig sig-object py" id="asyncio.loop.close">404<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.close" title="Link to this definition">¶</a></dt>405<dd><p>Close the event loop.</p>406<p>The loop must not be running when this function is called.407Any pending callbacks will be discarded.</p>408<p>This method clears all queues and shuts down the executor, but does409not wait for the executor to finish.</p>410<p>This method is idempotent and irreversible.  No other methods411should be called after the event loop is closed.</p>412</dd></dl>413 414<dl class="py method">415<dt class="sig sig-object py" id="asyncio.loop.shutdown_asyncgens">416<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">shutdown_asyncgens</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.shutdown_asyncgens" title="Link to this definition">¶</a></dt>417<dd><p>Schedule all currently open <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> objects to418close with an <a class="reference internal" href="../reference/expressions.html#agen.aclose" title="agen.aclose"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aclose()</span></code></a> call.  After calling this method,419the event loop will issue a warning if a new asynchronous generator420is iterated. This should be used to reliably finalize all scheduled421asynchronous generators.</p>422<p>Note that there is no need to call this function when423<a class="reference internal" href="asyncio-runner.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> is used.</p>424<p>Example:</p>425<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>426    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>427<span class="k">finally</span><span class="p">:</span>428    <span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">shutdown_asyncgens</span><span class="p">())</span>429    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>430</pre></div>431</div>432<div class="versionadded">433<p><span class="versionmodified added">Added in version 3.6.</span></p>434</div>435</dd></dl>436 437<dl class="py method">438<dt class="sig sig-object py" id="asyncio.loop.shutdown_default_executor">439<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">shutdown_default_executor</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.shutdown_default_executor" title="Link to this definition">¶</a></dt>440<dd><p>Schedule the closure of the default executor and wait for it to join all of441the threads in the <a class="reference internal" href="concurrent.futures.html#concurrent.futures.ThreadPoolExecutor" title="concurrent.futures.ThreadPoolExecutor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadPoolExecutor</span></code></a>.442Once this method has been called,443using the default executor with <a class="reference internal" href="#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_in_executor()</span></code></a>444will raise a <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>445<p>The <em>timeout</em> parameter specifies the amount of time446(in <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> seconds) the executor will be given to finish joining.447With the default, <code class="docutils literal notranslate"><span class="pre">None</span></code>,448the executor is allowed an unlimited amount of time.</p>449<p>If the <em>timeout</em> is reached, a <a class="reference internal" href="exceptions.html#RuntimeWarning" title="RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a> is emitted450and the default executor is terminated451without waiting for its threads to finish joining.</p>452<div class="admonition note">453<p class="admonition-title">Note</p>454<p>Do not call this method when using <a class="reference internal" href="asyncio-runner.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a>,455as the latter handles default executor shutdown automatically.</p>456</div>457<div class="versionadded">458<p><span class="versionmodified added">Added in version 3.9.</span></p>459</div>460<div class="versionchanged">461<p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>timeout</em> parameter.</p>462</div>463</dd></dl>464 465</section>466<section id="scheduling-callbacks">467<h3><a class="toc-backref" href="#id2" role="doc-backlink">Scheduling callbacks</a><a class="headerlink" href="#scheduling-callbacks" title="Link to this heading">¶</a></h3>468<dl class="py method">469<dt class="sig sig-object py" id="asyncio.loop.call_soon">470<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_soon</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon" title="Link to this definition">¶</a></dt>471<dd><p>Schedule the <em>callback</em> <a class="reference internal" href="../glossary.html#term-callback"><span class="xref std std-term">callback</span></a> to be called with472<em>args</em> arguments at the next iteration of the event loop.</p>473<p>Return an instance of <a class="reference internal" href="#asyncio.Handle" title="asyncio.Handle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Handle</span></code></a>,474which can be used later to cancel the callback.</p>475<p>Callbacks are called in the order in which they are registered.476Each callback will be called exactly once.</p>477<p>The optional keyword-only <em>context</em> argument specifies a478custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.479Callbacks use the current context when no <em>context</em> is provided.</p>480<p>Unlike <a class="reference internal" href="#asyncio.loop.call_soon_threadsafe" title="asyncio.loop.call_soon_threadsafe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon_threadsafe()</span></code></a>, this method is not thread-safe.</p>481</dd></dl>482 483<dl class="py method">484<dt class="sig sig-object py" id="asyncio.loop.call_soon_threadsafe">485<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_soon_threadsafe</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon_threadsafe" title="Link to this definition">¶</a></dt>486<dd><p>A thread-safe variant of <a class="reference internal" href="#asyncio.loop.call_soon" title="asyncio.loop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>. When scheduling callbacks from487another thread, this function <em>must</em> be used, since <code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code> is not488thread-safe.</p>489<p>This function is safe to be called from a reentrant context or signal handler,490however, it is not safe or fruitful to use the returned handle in such contexts.</p>491<p>Raises <a class="reference internal" href="exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if called on a loop that’s been closed.492This can happen on a secondary thread when the main application is493shutting down.</p>494<p>See the <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a>495section of the documentation.</p>496<div class="versionchanged">497<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>498for more details.</p>499</div>500</dd></dl>501 502<div class="admonition note" id="asyncio-pass-keywords">503<p class="admonition-title">Note</p>504<p>Most <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> scheduling functions don’t allow passing505keyword arguments.  To do that, use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>:</p>506<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># will schedule &quot;print(&quot;Hello&quot;, flush=True)&quot;</span>507<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span>508    <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="nb">print</span><span class="p">,</span> <span class="s2">&quot;Hello&quot;</span><span class="p">,</span> <span class="n">flush</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>509</pre></div>510</div>511<p>Using partial objects is usually more convenient than using lambdas,512as asyncio can render partial objects better in debug and error513messages.</p>514</div>515</section>516<section id="scheduling-delayed-callbacks">517<span id="asyncio-delayed-calls"></span><h3><a class="toc-backref" href="#id3" role="doc-backlink">Scheduling delayed callbacks</a><a class="headerlink" href="#scheduling-delayed-callbacks" title="Link to this heading">¶</a></h3>518<p>Event loop provides mechanisms to schedule callback functions519to be called at some point in the future.  Event loop uses monotonic520clocks to track time.</p>521<dl class="py method">522<dt class="sig sig-object py" id="asyncio.loop.call_later">523<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_later</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">delay</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_later" title="Link to this definition">¶</a></dt>524<dd><p>Schedule <em>callback</em> to be called after the given <em>delay</em>525number of seconds (can be either an int or a float).</p>526<p>An instance of <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TimerHandle</span></code></a> is returned which can527be used to cancel the callback.</p>528<p><em>callback</em> will be called exactly once.  If two callbacks are529scheduled for exactly the same time, the order in which they530are called is undefined.</p>531<p>The optional positional <em>args</em> will be passed to the callback when532it is called. Use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>533<a class="reference internal" href="#asyncio-pass-keywords"><span class="std std-ref">to pass keyword arguments</span></a> to534<em>callback</em>.</p>535<p>An optional keyword-only <em>context</em> argument allows specifying a536custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>callback</em> to run in.537The current context is used when no <em>context</em> is provided.</p>538<div class="admonition note">539<p class="admonition-title">Note</p>540<p>For performance, callbacks scheduled with <code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_later()</span></code>541may run up to one clock-resolution early (see542<code class="docutils literal notranslate"><span class="pre">time.get_clock_info('monotonic').resolution</span></code>).</p>543</div>544<div class="versionchanged">545<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>546for more details.</p>547</div>548<div class="versionchanged">549<p><span class="versionmodified changed">Changed in version 3.8: </span>In Python 3.7 and earlier with the default event loop implementation,550the <em>delay</em> could not exceed one day.551This has been fixed in Python 3.8.</p>552</div>553</dd></dl>554 555<dl class="py method">556<dt class="sig sig-object py" id="asyncio.loop.call_at">557<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_at</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">when</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_at" title="Link to this definition">¶</a></dt>558<dd><p>Schedule <em>callback</em> to be called at the given absolute timestamp559<em>when</em> (an int or a float), using the same time reference as560<a class="reference internal" href="#asyncio.loop.time" title="asyncio.loop.time"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.time()</span></code></a>.</p>561<p>This method’s behavior is the same as <a class="reference internal" href="#asyncio.loop.call_later" title="asyncio.loop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_later()</span></code></a>.</p>562<p>An instance of <a class="reference internal" href="#asyncio.TimerHandle" title="asyncio.TimerHandle"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.TimerHandle</span></code></a> is returned which can563be used to cancel the callback.</p>564<div class="admonition note">565<p class="admonition-title">Note</p>566<p>For performance, callbacks scheduled with <code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_at()</span></code>567may run up to one clock-resolution early (see568<code class="docutils literal notranslate"><span class="pre">time.get_clock_info('monotonic').resolution</span></code>).</p>569</div>570<div class="versionchanged">571<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>572for more details.</p>573</div>574<div class="versionchanged">575<p><span class="versionmodified changed">Changed in version 3.8: </span>In Python 3.7 and earlier with the default event loop implementation,576the difference between <em>when</em> and the current time could not exceed577one day.  This has been fixed in Python 3.8.</p>578</div>579</dd></dl>580 581<dl class="py method">582<dt class="sig sig-object py" id="asyncio.loop.time">583<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">time</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.time" title="Link to this definition">¶</a></dt>584<dd><p>Return the current time, as a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> value, according to585the event loop’s internal monotonic clock.</p>586</dd></dl>587 588<div class="admonition note">589<p class="admonition-title">Note</p>590<div class="versionchanged">591<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>)592should not exceed one day.  This has been fixed in Python 3.8.</p>593</div>594</div>595<div class="admonition seealso">596<p class="admonition-title">See also</p>597<p>The <a class="reference internal" href="asyncio-task.html#asyncio.sleep" title="asyncio.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.sleep()</span></code></a> function.</p>598</div>599</section>600<section id="creating-futures-and-tasks">601<h3><a class="toc-backref" href="#id4" role="doc-backlink">Creating Futures and Tasks</a><a class="headerlink" href="#creating-futures-and-tasks" title="Link to this heading">¶</a></h3>602<dl class="py method">603<dt class="sig sig-object py" id="asyncio.loop.create_future">604<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_future</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_future" title="Link to this definition">¶</a></dt>605<dd><p>Create an <a class="reference internal" href="asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> object attached to the event loop.</p>606<p>This is the preferred way to create Futures in asyncio. This lets607third-party event loops provide alternative implementations of608the Future object (with better performance or instrumentation).</p>609<div class="versionadded">610<p><span class="versionmodified added">Added in version 3.5.2.</span></p>611</div>612</dd></dl>613 614<dl class="py method">615<dt class="sig sig-object py" id="asyncio.loop.create_task">616<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_task</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">coro</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">eager_start</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_task" title="Link to this definition">¶</a></dt>617<dd><p>Schedule the execution of <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">coroutine</span></a> <em>coro</em>.618Return a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object.</p>619<p>Third-party event loops can use their own subclass of <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>620for interoperability. In this case, the result type is a subclass621of <code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code>.</p>622<p>The full function signature is largely the same as that of the623<a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> constructor (or factory) - all of the keyword arguments to624this function are passed through to that interface.</p>625<p>If the <em>name</em> argument is provided and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is set as626the name of the task using <a class="reference internal" href="asyncio-task.html#asyncio.Task.set_name" title="asyncio.Task.set_name"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Task.set_name()</span></code></a>.</p>627<p>An optional keyword-only <em>context</em> argument allows specifying a628custom <a class="reference internal" href="contextvars.html#contextvars.Context" title="contextvars.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">contextvars.Context</span></code></a> for the <em>coro</em> to run in.629The current context copy is created when no <em>context</em> is provided.</p>630<p>An optional keyword-only <em>eager_start</em> argument allows specifying631if the task should execute eagerly during the call to create_task,632or be scheduled later. If <em>eager_start</em> is not passed the mode set633by <a class="reference internal" href="#asyncio.loop.set_task_factory" title="asyncio.loop.set_task_factory"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.set_task_factory()</span></code></a> will be used.</p>634<div class="versionchanged">635<p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p>636</div>637<div class="versionchanged">638<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p>639</div>640<div class="versionchanged">641<p><span class="versionmodified changed">Changed in version 3.13.3: </span>Added <code class="docutils literal notranslate"><span class="pre">kwargs</span></code> which passes on arbitrary extra parameters, including  <code class="docutils literal notranslate"><span class="pre">name</span></code> and <code class="docutils literal notranslate"><span class="pre">context</span></code>.</p>642</div>643<div class="versionchanged">644<p><span class="versionmodified changed">Changed in version 3.13.4: </span>Rolled back the change that passes on <em>name</em> and <em>context</em> (if it is None),645while still passing on other arbitrary keyword arguments (to avoid breaking backwards compatibility with 3.13.3).</p>646</div>647<div class="versionchanged">648<p><span class="versionmodified changed">Changed in version 3.14: </span>All <em>kwargs</em> are now passed on. The <em>eager_start</em> parameter works with eager task factories.</p>649</div>650</dd></dl>651 652<dl class="py method">653<dt class="sig sig-object py" id="asyncio.loop.set_task_factory">654<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">set_task_factory</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">factory</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_task_factory" title="Link to this definition">¶</a></dt>655<dd><p>Set a task factory that will be used by656<a class="reference internal" href="#asyncio.loop.create_task" title="asyncio.loop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_task()</span></code></a>.</p>657<p>If <em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> the default task factory will be set.658Otherwise, <em>factory</em> must be a <em>callable</em> with the signature matching659<code class="docutils literal notranslate"><span class="pre">(loop,</span> <span class="pre">coro,</span> <span class="pre">**kwargs)</span></code>, where <em>loop</em> is a reference to the active660event loop, and <em>coro</em> is a coroutine object.  The callable661must pass on all <em>kwargs</em>, and return a <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>-compatible object.</p>662<div class="versionchanged">663<p><span class="versionmodified changed">Changed in version 3.13.3: </span>Required that all <em>kwargs</em> are passed on to <a class="reference internal" href="asyncio-task.html#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Task</span></code></a>.</p>664</div>665<div class="versionchanged">666<p><span class="versionmodified changed">Changed in version 3.13.4: </span><em>name</em> is no longer passed to task factories. <em>context</em> is no longer passed667to task factories if it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>668<div class="versionchanged">669<p><span class="versionmodified changed">Changed in version 3.14: </span><em>name</em> and <em>context</em> are now unconditionally passed on to task factories again.</p>670</div>671</div>672</dd></dl>673 674<dl class="py method">675<dt class="sig sig-object py" id="asyncio.loop.get_task_factory">676<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">get_task_factory</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_task_factory" title="Link to this definition">¶</a></dt>677<dd><p>Return a task factory or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the default one is in use.</p>678</dd></dl>679 680</section>681<section id="opening-network-connections">682<h3><a class="toc-backref" href="#id5" role="doc-backlink">Opening network connections</a><a class="headerlink" href="#opening-network-connections" title="Link to this heading">¶</a></h3>683<dl class="py method">684<dt class="sig sig-object py" id="asyncio.loop.create_connection">685<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_connection</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">host</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">port</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">family</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">proto</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">local_addr</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">server_hostname</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">happy_eyeballs_delay</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">interleave</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">all_errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_connection" title="Link to this definition">¶</a></dt>686<dd><p>Open a streaming transport connection to a given687address specified by <em>host</em> and <em>port</em>.</p>688<p>The socket family can be either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> or689<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> depending on <em>host</em> (or the <em>family</em>690argument, if provided).</p>691<p>The socket type will be <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>.</p>692<p><em>protocol_factory</em> must be a callable returning an693<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio protocol</span></a> implementation.</p>694<p>This method will try to establish the connection in the background.695When successful, it returns a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> pair.</p>696<p>The chronological synopsis of the underlying operation is as follows:</p>697<ol class="arabic simple">698<li><p>The connection is established and a <a class="reference internal" href="asyncio-protocol.html#asyncio-transport"><span class="std std-ref">transport</span></a>699is created for it.</p></li>700<li><p><em>protocol_factory</em> is called without arguments and is expected to701return a <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> instance.</p></li>702<li><p>The protocol instance is coupled with the transport by calling its703<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseProtocol.connection_made" title="asyncio.BaseProtocol.connection_made"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connection_made()</span></code></a> method.</p></li>704<li><p>A <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> tuple is returned on success.</p></li>705</ol>706<p>The created transport is an implementation-dependent bidirectional707stream.</p>708<p>Other arguments:</p>709<ul>710<li><p><em>ssl</em>: if given and not false, a SSL/TLS transport is created711(by default a plain TCP transport is created).  If <em>ssl</em> is712a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> object, this context is used to create713the transport; if <em>ssl</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, a default context returned714from <a class="reference internal" href="ssl.html#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.create_default_context()</span></code></a> is used.</p>715<div class="admonition seealso">716<p class="admonition-title">See also</p>717<p><a class="reference internal" href="ssl.html#ssl-security"><span class="std std-ref">SSL/TLS security considerations</span></a></p>718</div>719</li>720<li><p><em>server_hostname</em> sets or overrides the hostname that the target721server’s certificate will be matched against.  Should only be passed722if <em>ssl</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>.  By default the value of the <em>host</em> argument723is used.  If <em>host</em> is empty, there is no default and you must pass a724value for <em>server_hostname</em>.  If <em>server_hostname</em> is an empty725string, hostname matching is disabled (which is a serious security726risk, allowing for potential man-in-the-middle attacks).</p></li>727<li><p><em>family</em>, <em>proto</em>, <em>flags</em> are the optional address family, protocol728and flags to be passed through to getaddrinfo() for <em>host</em> resolution.729If given, these should all be integers from the corresponding730<a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module constants.</p></li>731<li><p><em>happy_eyeballs_delay</em>, if given, enables Happy Eyeballs for this732connection. It should733be a floating-point number representing the amount of time in seconds734to wait for a connection attempt to complete, before starting the next735attempt in parallel. This is the “Connection Attempt Delay” as defined736in <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 class="docutils literal notranslate"><span class="pre">0.25</span></code>737(250 milliseconds).</p></li>738<li><p><em>interleave</em> controls address reordering when a host name resolves to739multiple IP addresses.740If <code class="docutils literal notranslate"><span class="pre">0</span></code> or unspecified, no reordering is done, and addresses are741tried in the order returned by <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a>. If a positive integer742is specified, the addresses are interleaved by address family, and the743given integer is interpreted as “First Address Family Count” as defined744in <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 class="docutils literal notranslate"><span class="pre">0</span></code> if <em>happy_eyeballs_delay</em> is not745specified, and <code class="docutils literal notranslate"><span class="pre">1</span></code> if it is.</p></li>746<li><p><em>sock</em>, if given, should be an existing, already connected747<a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> object to be used by the transport.748If <em>sock</em> is given, none of <em>host</em>, <em>port</em>, <em>family</em>, <em>proto</em>, <em>flags</em>,749<em>happy_eyeballs_delay</em>, <em>interleave</em>750and <em>local_addr</em> should be specified.</p>751<div class="admonition note">752<p class="admonition-title">Note</p>753<p>The <em>sock</em> argument transfers ownership of the socket to the754transport created. To close the socket, call the transport’s755<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>756</div>757</li>758<li><p><em>local_addr</em>, if given, is a <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> tuple used759to bind the socket locally.  The <em>local_host</em> and <em>local_port</em>760are looked up using <code class="docutils literal notranslate"><span class="pre">getaddrinfo()</span></code>, similarly to <em>host</em> and <em>port</em>.</p></li>761<li><p><em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds762to wait for the TLS handshake to complete before aborting the connection.763<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p></li>764<li><p><em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown765to complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">30.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code>766(default).</p></li>767<li><p><em>all_errors</em> determines what exceptions are raised when a connection cannot768be created. By default, only a single <code class="docutils literal notranslate"><span class="pre">Exception</span></code> is raised: the first769exception if there is only one or all errors have same message, or a single770<code class="docutils literal notranslate"><span class="pre">OSError</span></code> with the error messages combined. When <code class="docutils literal notranslate"><span class="pre">all_errors</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>,771an <code class="docutils literal notranslate"><span class="pre">ExceptionGroup</span></code> will be raised containing all exceptions (even if there772is only one).</p></li>773</ul>774<div class="versionchanged">775<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 class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>.</p>776</div>777<div class="versionchanged">778<p><span class="versionmodified changed">Changed in version 3.6: </span>The socket option <a class="reference internal" href="socket.html#socket-unix-constants"><span class="std std-ref">socket.TCP_NODELAY</span></a> is set by default779for all TCP connections.</p>780</div>781<div class="versionchanged">782<p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.</p>783</div>784<div class="versionchanged">785<p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>happy_eyeballs_delay</em> and <em>interleave</em> parameters.</p>786<p>Happy Eyeballs Algorithm: Success with Dual-Stack Hosts.787When a server’s IPv4 path and protocol are working, but the server’s788IPv6 path and protocol are not working, a dual-stack client789application experiences significant connection delay compared to an790IPv4-only client.  This is undesirable because it causes the791dual-stack client to have a worse user experience.  This document792specifies requirements for algorithms that reduce this user-visible793delay and provides an algorithm.</p>794<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>795</div>796<div class="versionchanged">797<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>798</div>799<div class="versionchanged">800<p><span class="versionmodified changed">Changed in version 3.12: </span><em>all_errors</em> was added.</p>801</div>802<div class="admonition seealso">803<p class="admonition-title">See also</p>804<p>The <a class="reference internal" href="asyncio-stream.html#asyncio.open_connection" title="asyncio.open_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_connection()</span></code></a> function is a high-level alternative805API.  It returns a pair of (<a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a>, <a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>)806that can be used directly in async/await code.</p>807</div>808</dd></dl>809 810<dl class="py method">811<dt class="sig sig-object py" id="asyncio.loop.create_datagram_endpoint">812<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_datagram_endpoint</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">local_addr</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">remote_addr</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">family</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">proto</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">reuse_port</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allow_broadcast</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_datagram_endpoint" title="Link to this definition">¶</a></dt>813<dd><p>Create a datagram connection.</p>814<p>The socket family can be either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>,815<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>, or <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>,816depending on <em>host</em> (or the <em>family</em> argument, if provided).</p>817<p>The socket type will be <a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a>.</p>818<p><em>protocol_factory</em> must be a callable returning a819<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</p>820<p>A tuple of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> is returned on success.</p>821<p>Other arguments:</p>822<ul>823<li><p><em>local_addr</em>, if given, is a <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> tuple used824to bind the socket locally.  The <em>local_host</em> and <em>local_port</em>825are looked up using <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a>.</p>826<div class="admonition note">827<p class="admonition-title">Note</p>828<p>On Windows, when using the proactor event loop with <code class="docutils literal notranslate"><span class="pre">local_addr=None</span></code>,829an <a class="reference internal" href="exceptions.html#OSError" title="OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> with <code class="xref py py-attr docutils literal notranslate"><span class="pre">errno.WSAEINVAL</span></code> will be raised830when running it.</p>831</div>832</li>833<li><p><em>remote_addr</em>, if given, is a <code class="docutils literal notranslate"><span class="pre">(remote_host,</span> <span class="pre">remote_port)</span></code> tuple used834to connect the socket to a remote address.  The <em>remote_host</em> and835<em>remote_port</em> are looked up using <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a>.</p></li>836<li><p><em>family</em>, <em>proto</em>, <em>flags</em> are the optional address family, protocol837and flags to be passed through to <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> for <em>host</em>838resolution. If given, these should all be integers from the839corresponding <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module constants.</p></li>840<li><p><em>reuse_port</em> tells the kernel to allow this endpoint to be bound to the841same port as other existing endpoints are bound to, so long as they all842set this flag when being created. This option is not supported on Windows843and some Unixes. If the <a class="reference internal" href="socket.html#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEPORT</span></a> constant is not844defined then this capability is unsupported.</p></li>845<li><p><em>allow_broadcast</em> tells the kernel to allow this endpoint to send846messages to the broadcast address.</p></li>847<li><p><em>sock</em> can optionally be specified in order to use a preexisting,848already connected, <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> object to be used by the849transport. If specified, <em>local_addr</em> and <em>remote_addr</em> should be omitted850(must be <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>).</p>851<div class="admonition note">852<p class="admonition-title">Note</p>853<p>The <em>sock</em> argument transfers ownership of the socket to the854transport created. To close the socket, call the transport’s855<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>856</div>857</li>858</ul>859<p>See <a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-client-protocol"><span class="std std-ref">UDP echo client protocol</span></a> and860<a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-server-protocol"><span class="std std-ref">UDP echo server protocol</span></a> examples.</p>861<div class="versionchanged">862<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>,863<em>allow_broadcast</em>, and <em>sock</em> parameters were added.</p>864</div>865<div class="versionchanged">866<p><span class="versionmodified changed">Changed in version 3.8: </span>Added support for Windows.</p>867</div>868<div class="versionchanged">869<p><span class="versionmodified changed">Changed in version 3.8.1: </span>The <em>reuse_address</em> parameter is no longer supported, as using870<a class="reference internal" href="socket.html#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEADDR</span></a>871poses a significant security concern for872UDP. Explicitly passing <code class="docutils literal notranslate"><span class="pre">reuse_address=True</span></code> will raise an exception.</p>873<p>When multiple processes with differing UIDs assign sockets to an874identical UDP socket address with <code class="docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code>, incoming packets can875become randomly distributed among the sockets.</p>876<p>For supported platforms, <em>reuse_port</em> can be used as a replacement for877similar functionality. With <em>reuse_port</em>,878<a class="reference internal" href="socket.html#socket-unix-constants"><span class="std std-ref">socket.SO_REUSEPORT</span></a>879is used instead, which specifically880prevents processes with differing UIDs from assigning sockets to the same881socket address.</p>882</div>883<div class="versionchanged">884<p><span class="versionmodified changed">Changed in version 3.11: </span>The <em>reuse_address</em> parameter, disabled since Python 3.8.1,8853.7.6 and 3.6.10, has been entirely removed.</p>886</div>887</dd></dl>888 889<dl class="py method">890<dt class="sig sig-object py" id="asyncio.loop.create_unix_connection">891<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_unix_connection</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">path</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">server_hostname</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_connection" title="Link to this definition">¶</a></dt>892<dd><p>Create a Unix connection.</p>893<p>The socket family will be <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>; socket894type will be <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>.</p>895<p>A tuple of <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> is returned on success.</p>896<p><em>path</em> is the name of a Unix domain socket and is required,897unless a <em>sock</em> parameter is specified.  Abstract Unix sockets,898<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, and <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> paths are899supported.</p>900<p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> method901for information about arguments to this method.</p>902<div class="availability docutils container">903<p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p>904</div>905<div class="versionchanged">906<p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.907The <em>path</em> parameter can now be a <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p>908</div>909<div class="versionchanged">910<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>911</div>912</dd></dl>913 914</section>915<section id="creating-network-servers">916<h3><a class="toc-backref" href="#id6" role="doc-backlink">Creating network servers</a><a class="headerlink" href="#creating-network-servers" title="Link to this heading">¶</a></h3>917<dl class="py method" id="loop-create-server">918<dt class="sig sig-object py" id="asyncio.loop.create_server">919<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_server</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">host</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">port</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">family</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">socket.AF_UNSPEC</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">socket.AI_PASSIVE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">backlog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">reuse_address</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">reuse_port</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">keep_alive</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">start_serving</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_server" title="Link to this definition">¶</a></dt>920<dd><p>Create a TCP server (socket type <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a>) listening921on <em>port</em> of the <em>host</em> address.</p>922<p>Returns a <a class="reference internal" href="#asyncio.Server" title="asyncio.Server"><code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code></a> object.</p>923<p>Arguments:</p>924<ul>925<li><p><em>protocol_factory</em> must be a callable returning a926<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</p></li>927<li><p>The <em>host</em> parameter can be set to several types which determine where928the server would be listening:</p>929<ul class="simple">930<li><p>If <em>host</em> is a string, the TCP server is bound to a single network931interface specified by <em>host</em>.</p></li>932<li><p>If <em>host</em> is a sequence of strings, the TCP server is bound to all933network interfaces specified by the sequence.</p></li>934<li><p>If <em>host</em> is an empty string or <code class="docutils literal notranslate"><span class="pre">None</span></code>, all interfaces are935assumed and a list of multiple sockets will be returned (most likely936one for IPv4 and another one for IPv6).</p></li>937</ul>938</li>939<li><p>The <em>port</em> parameter can be set to specify which port the server should940listen on. If <code class="docutils literal notranslate"><span class="pre">0</span></code> or <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), a random unused port will941be selected (note that if <em>host</em> resolves to multiple network interfaces,942a different random port will be selected for each interface).</p></li>943<li><p><em>family</em> can be set to either <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.AF_INET</span></code></a> or944<a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> to force the socket to use IPv4 or IPv6.945If not set, the <em>family</em> will be determined from host name946(defaults to <a class="reference internal" href="socket.html#socket.AF_UNSPEC" title="socket.AF_UNSPEC"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNSPEC</span></code></a>).</p></li>947<li><p><em>flags</em> is a bitmask for <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a>.</p></li>948<li><p><em>sock</em> can optionally be specified in order to use a preexisting949socket object. If specified, <em>host</em> and <em>port</em> must not be specified.</p>950<div class="admonition note">951<p class="admonition-title">Note</p>952<p>The <em>sock</em> argument transfers ownership of the socket to the953server created. To close the socket, call the server’s954<a class="reference internal" href="#asyncio.Server.close" title="asyncio.Server.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>955</div>956</li>957<li><p><em>backlog</em> is the maximum number of queued connections passed to958<a class="reference internal" href="socket.html#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a> (defaults to 100).</p></li>959<li><p><em>ssl</em> can be set to an <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> instance to enable960TLS over the accepted connections.</p></li>961<li><p><em>reuse_address</em> tells the kernel to reuse a local socket in962<code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> state, without waiting for its natural timeout to963expire. If not specified will automatically be set to <code class="docutils literal notranslate"><span class="pre">True</span></code> on964Unix.</p></li>965<li><p><em>reuse_port</em> tells the kernel to allow this endpoint to be bound to the966same port as other existing endpoints are bound to, so long as they all967set this flag when being created. This option is not supported on968Windows.</p></li>969<li><p><em>keep_alive</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> keeps connections active by enabling the970periodic transmission of messages.</p></li>971</ul>972<div class="versionchanged">973<p><span class="versionmodified changed">Changed in version 3.13: </span>Added the <em>keep_alive</em> parameter.</p>974</div>975<ul class="simple">976<li><p><em>ssl_handshake_timeout</em> is (for a TLS server) the time in seconds to wait977for the TLS handshake to complete before aborting the connection.978<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p></li>979<li><p><em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown980to complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">30.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code>981(default).</p></li>982<li><p><em>start_serving</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) causes the created server983to start accepting connections immediately.  When set to <code class="docutils literal notranslate"><span class="pre">False</span></code>,984the user should await on <a class="reference internal" href="#asyncio.Server.start_serving" title="asyncio.Server.start_serving"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Server.start_serving()</span></code></a> or985<a class="reference internal" href="#asyncio.Server.serve_forever" title="asyncio.Server.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Server.serve_forever()</span></code></a> to make the server to start accepting986connections.</p></li>987</ul>988<div class="versionchanged">989<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 class="xref py py-class docutils literal notranslate"><span class="pre">ProactorEventLoop</span></code></a>.</p>990</div>991<div class="versionchanged">992<p><span class="versionmodified changed">Changed in version 3.5.1: </span>The <em>host</em> parameter can be a sequence of strings.</p>993</div>994<div class="versionchanged">995<p><span class="versionmodified changed">Changed in version 3.6: </span>Added <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.996The socket option <a class="reference internal" href="socket.html#socket-unix-constants"><span class="std std-ref">socket.TCP_NODELAY</span></a> is set by default997for all TCP connections.</p>998</div>999<div class="versionchanged">1000<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>1001</div>1002<div class="admonition seealso">1003<p class="admonition-title">See also</p>1004<p>The <a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_server()</span></code></a> function is a higher-level alternative API1005that returns a pair of <a class="reference internal" href="asyncio-stream.html#asyncio.StreamReader" title="asyncio.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="asyncio-stream.html#asyncio.StreamWriter" title="asyncio.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>1006that can be used in an async/await code.</p>1007</div>1008</dd></dl>1009 1010<dl class="py method">1011<dt class="sig sig-object py" id="asyncio.loop.create_unix_server">1012<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_unix_server</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">path</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">backlog</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">100</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">start_serving</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">cleanup_socket</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_server" title="Link to this definition">¶</a></dt>1013<dd><p>Similar to <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> but works with the1014<a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> socket family.</p>1015<p><em>path</em> is the name of a Unix domain socket, and is required,1016unless a <em>sock</em> argument is provided.  Abstract Unix sockets,1017<a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>, and <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> paths1018are supported.</p>1019<p>If <em>cleanup_socket</em> is true then the Unix socket will automatically1020be removed from the filesystem when the server is closed, unless the1021socket has been replaced after the server has been created.</p>1022<p>See the documentation of the <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a> method1023for information about arguments to this method.</p>1024<div class="availability docutils container">1025<p><a class="reference internal" href="intro.html#availability"><span class="std std-ref">Availability</span></a>: Unix.</p>1026</div>1027<div class="versionchanged">1028<p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.1029The <em>path</em> parameter can now be a <a class="reference internal" href="pathlib.html#pathlib.Path" title="pathlib.Path"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a> object.</p>1030</div>1031<div class="versionchanged">1032<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>1033</div>1034<div class="versionchanged">1035<p><span class="versionmodified changed">Changed in version 3.13: </span>Added the <em>cleanup_socket</em> parameter.</p>1036</div>1037</dd></dl>1038 1039<dl class="py method">1040<dt class="sig sig-object py" id="asyncio.loop.connect_accepted_socket">1041<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">connect_accepted_socket</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">protocol_factory</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sock</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_accepted_socket" title="Link to this definition">¶</a></dt>1042<dd><p>Wrap an already accepted connection into a transport/protocol pair.</p>1043<p>This method can be used by servers that accept connections outside1044of asyncio but that use asyncio to handle them.</p>1045<p>Parameters:</p>1046<ul>1047<li><p><em>protocol_factory</em> must be a callable returning a1048<a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">protocol</span></a> implementation.</p></li>1049<li><p><em>sock</em> is a preexisting socket object returned from1050<a class="reference internal" href="socket.html#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.accept</span></code></a>.</p>1051<div class="admonition note">1052<p class="admonition-title">Note</p>1053<p>The <em>sock</em> argument transfers ownership of the socket to the1054transport created. To close the socket, call the transport’s1055<a class="reference internal" href="asyncio-protocol.html#asyncio.BaseTransport.close" title="asyncio.BaseTransport.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>1056</div>1057</li>1058<li><p><em>ssl</em> can be set to an <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> to enable SSL over1059the accepted connections.</p></li>1060<li><p><em>ssl_handshake_timeout</em> is (for an SSL connection) the time in seconds to1061wait for the SSL handshake to complete before aborting the connection.1062<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p></li>1063<li><p><em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown1064to complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">30.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code>1065(default).</p></li>1066</ul>1067<p>Returns a <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> pair.</p>1068<div class="versionadded">1069<p><span class="versionmodified added">Added in version 3.5.3.</span></p>1070</div>1071<div class="versionchanged">1072<p><span class="versionmodified changed">Changed in version 3.7: </span>Added the <em>ssl_handshake_timeout</em> parameter.</p>1073</div>1074<div class="versionchanged">1075<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>1076</div>1077</dd></dl>1078 1079</section>1080<section id="transferring-files">1081<h3><a class="toc-backref" href="#id7" role="doc-backlink">Transferring files</a><a class="headerlink" href="#transferring-files" title="Link to this heading">¶</a></h3>1082<dl class="py method">1083<dt class="sig sig-object py" id="asyncio.loop.sendfile">1084<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">sendfile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">transport</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">file</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">offset</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">count</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">fallback</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sendfile" title="Link to this definition">¶</a></dt>1085<dd><p>Send a <em>file</em> over a <em>transport</em>.  Return the total number of bytes1086sent.</p>1087<p>The method uses high-performance <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">os.sendfile()</span></code></a> if available.</p>1088<p><em>file</em> must be a regular file object opened in binary mode.</p>1089<p><em>offset</em> tells from where to start reading the file. If specified,1090<em>count</em> is the total number of bytes to transmit as opposed to1091sending the file until EOF is reached. File position is always updated,1092even when this method raises an error, and1093<a class="reference internal" href="io.html#io.IOBase.tell" title="io.IOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.tell()</span></code></a> can be used to obtain the actual1094number of bytes sent.</p>1095<p><em>fallback</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> makes asyncio to manually read and send1096the file when the platform does not support the sendfile system call1097(e.g. Windows or SSL socket on Unix).</p>1098<p>Raise <a class="reference internal" href="asyncio-exceptions.html#asyncio.SendfileNotAvailableError" title="asyncio.SendfileNotAvailableError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SendfileNotAvailableError</span></code></a> if the system does not support1099the <em>sendfile</em> syscall and <em>fallback</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>1100<div class="versionadded">1101<p><span class="versionmodified added">Added in version 3.7.</span></p>1102</div>1103</dd></dl>1104 1105</section>1106<section id="tls-upgrade">1107<h3><a class="toc-backref" href="#id8" role="doc-backlink">TLS Upgrade</a><a class="headerlink" href="#tls-upgrade" title="Link to this heading">¶</a></h3>1108<dl class="py method">1109<dt class="sig sig-object py" id="asyncio.loop.start_tls">1110<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">start_tls</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">transport</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">protocol</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">sslcontext</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">server_side</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">server_hostname</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_handshake_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ssl_shutdown_timeout</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.start_tls" title="Link to this definition">¶</a></dt>1111<dd><p>Upgrade an existing transport-based connection to TLS.</p>1112<p>Create a TLS coder/decoder instance and insert it between the <em>transport</em>1113and the <em>protocol</em>. The coder/decoder implements both <em>transport</em>-facing1114protocol and <em>protocol</em>-facing transport.</p>1115<p>Return the created two-interface instance. After <em>await</em>, the <em>protocol</em>1116must stop using the original <em>transport</em> and communicate with the returned1117object only because the coder caches <em>protocol</em>-side data and sporadically1118exchanges extra TLS session packets with <em>transport</em>.</p>1119<p>In some situations (e.g. when the passed transport is already closing) this1120may return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>1121<p>Parameters:</p>1122<ul class="simple">1123<li><p><em>transport</em> and <em>protocol</em> instances that methods like1124<a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_server()</span></code></a> and1125<a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_connection()</span></code></a> return.</p></li>1126<li><p><em>sslcontext</em>: a configured instance of <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a>.</p></li>1127<li><p><em>server_side</em> pass <code class="docutils literal notranslate"><span class="pre">True</span></code> when a server-side connection is being1128upgraded (like the one created by <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_server()</span></code></a>).</p></li>1129<li><p><em>server_hostname</em>: sets or overrides the host name that the target1130server’s certificate will be matched against.</p></li>1131<li><p><em>ssl_handshake_timeout</em> is (for a TLS connection) the time in seconds to1132wait for the TLS handshake to complete before aborting the connection.1133<code class="docutils literal notranslate"><span class="pre">60.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code> (default).</p></li>1134<li><p><em>ssl_shutdown_timeout</em> is the time in seconds to wait for the SSL shutdown1135to complete before aborting the connection. <code class="docutils literal notranslate"><span class="pre">30.0</span></code> seconds if <code class="docutils literal notranslate"><span class="pre">None</span></code>1136(default).</p></li>1137</ul>1138<div class="versionadded">1139<p><span class="versionmodified added">Added in version 3.7.</span></p>1140</div>1141<div class="versionchanged">1142<p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>ssl_shutdown_timeout</em> parameter.</p>1143</div>1144</dd></dl>1145 1146</section>1147<section id="watching-file-descriptors">1148<h3><a class="toc-backref" href="#id9" role="doc-backlink">Watching file descriptors</a><a class="headerlink" href="#watching-file-descriptors" title="Link to this heading">¶</a></h3>1149<dl class="py method">1150<dt class="sig sig-object py" id="asyncio.loop.add_reader">1151<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">add_reader</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fd</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_reader" title="Link to this definition">¶</a></dt>1152<dd><p>Start monitoring the <em>fd</em> file descriptor for read availability and1153invoke <em>callback</em> with the specified arguments once <em>fd</em> is available for1154reading.</p>1155<p>Any preexisting callback registered for <em>fd</em> is cancelled and replaced by1156<em>callback</em>.</p>1157</dd></dl>1158 1159<dl class="py method">1160<dt class="sig sig-object py" id="asyncio.loop.remove_reader">1161<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">remove_reader</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fd</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_reader" title="Link to this definition">¶</a></dt>1162<dd><p>Stop monitoring the <em>fd</em> file descriptor for read availability. Returns1163<code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>fd</em> was previously being monitored for reads.</p>1164</dd></dl>1165 1166<dl class="py method">1167<dt class="sig sig-object py" id="asyncio.loop.add_writer">1168<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">add_writer</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fd</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">callback</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_writer" title="Link to this definition">¶</a></dt>1169<dd><p>Start monitoring the <em>fd</em> file descriptor for write availability and1170invoke <em>callback</em> with the specified arguments <em>args</em> once <em>fd</em> is1171available for writing.</p>1172<p>Any preexisting callback registered for <em>fd</em> is cancelled and replaced by1173<em>callback</em>.</p>1174<p>Use <a class="reference internal" href="functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></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>1175</dd></dl>1176 1177<dl class="py method">1178<dt class="sig sig-object py" id="asyncio.loop.remove_writer">1179<span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">remove_writer</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">fd</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_writer" title="Link to this definition">¶</a></dt>1180<dd><p>Stop monitoring the <em>fd</em> file descriptor for write availability. Returns1181<code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>fd</em> was previously being monitored for writes.</p>1182</dd></dl>1183 1184<p>See also <a class="reference internal" href="asyncio-platforms.html#asyncio-platform-support"><span class="std std-ref">Platform Support</span></a> section1185for some limitations of these methods.</p>1186</section>1187<section id="working-with-socket-objects-directly">1188<h3><a class="toc-backref" href="#id10" role="doc-backlink">Working with socket objects directly</a><a class="headerlink" href="#working-with-socket-objects-directly" title="Link to this heading">¶</a></h3>1189<p>In general, protocol implementations that use transport-based APIs1190such as <a class="reference internal" href="#asyncio.loop.create_connection" title="asyncio.loop.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_connection()</span></code></a> and <a class="reference internal" href="#asyncio.loop.create_server" title="asyncio.loop.create_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_server()</span></code></a>1191are faster than implementations that work with sockets directly.1192However, there are some use cases when performance is not critical, and1193working with <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> objects directly is more1194convenient.</p>1195<dl class="py method">1196<dt class="sig sig-object py" id="asyncio.loop.sock_recv">1197<em class="property"><span class="k"><span class="pre">async</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">sock_recv</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">sock</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">nbytes</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_recv" title="Link to this definition">¶</a></dt>1198<dd><p>Receive up to <em>nbytes</em> from <em>sock</em>.  Asynchronous version of1199<a class="reference internal" href="socket.html#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.recv()</span></code></a>.</p>1200<p>Return the received data as a bytes object.</p>

Showing the first 1,200 of 2374 lines. Download the file for the rest.