Team Ai
Apppublic

parthtamu/rag-code-assistant

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
asyncio-runner.html534 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="Runners" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/asyncio-runner.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." />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-runner_0cf58783.png" />15<meta property="og:image:alt" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." />16<meta name="description" content="Source code: Lib/asyncio/runners.py This section outlines high-level asyncio primitives to run asyncio code. They are built on top of an event loop with the aim to simplify async code usage for com..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20    <title>Runners &#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="Coroutines and Tasks" href="asyncio-task.html" />43    <link rel="prev" title="asyncio — Asynchronous I/O" href="asyncio.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-runner.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="#">Runners</a><ul>108<li><a class="reference internal" href="#running-an-asyncio-program">Running an asyncio Program</a></li>109<li><a class="reference internal" href="#runner-context-manager">Runner context manager</a></li>110<li><a class="reference internal" href="#handling-keyboard-interruption">Handling Keyboard Interruption</a></li>111</ul>112</li>113</ul>114 115  </div>116  <div>117    <h4>Previous topic</h4>118    <p class="topless"><a href="asyncio.html"119                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></p>120  </div>121  <div>122    <h4>Next topic</h4>123    <p class="topless"><a href="asyncio-task.html"124                          title="next chapter">Coroutines and Tasks</a></p>125  </div>126  <script>127    document.addEventListener('DOMContentLoaded', () => {128        const title = document.querySelector('meta[property="og:title"]').content;129        const elements = document.querySelectorAll('.improvepage');130        const pageurl = window.location.href.split('?')[0];131        elements.forEach(element => {132            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));133            url.searchParams.set('pagetitle', title);134            url.searchParams.set('pageurl', pageurl);135            url.searchParams.set('pagesource', "library/asyncio-runner.rst");136            element.href = url.toString();137        });138    });139  </script>140  <div role="note" aria-label="source link">141    <h3>This page</h3>142    <ul class="this-page-menu">143      <li><a href="../bugs.html">Report a bug</a></li>144      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>145      <li>146        <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-runner.rst?plain=1"147            rel="nofollow">Show source148        </a>149      </li>150      151    </ul>152  </div>153        </nav>154    </div>155</div>156 157  158    <div class="related" role="navigation" aria-label="Related">159      <h3>Navigation</h3>160      <ul>161        <li class="right" style="margin-right: 10px">162          <a href="../genindex.html" title="General Index"163             accesskey="I">index</a></li>164        <li class="right" >165          <a href="../py-modindex.html" title="Python Module Index"166             >modules</a> |</li>167        <li class="right" >168          <a href="asyncio-task.html" title="Coroutines and Tasks"169             accesskey="N">next</a> |</li>170        <li class="right" >171          <a href="asyncio.html" title="asyncio — Asynchronous I/O"172             accesskey="P">previous</a> |</li>173 174          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>175          <li><a href="https://www.python.org/">Python</a> &#187;</li>176          <li class="switchers">177            <div class="language_switcher_placeholder"></div>178            <div class="version_switcher_placeholder"></div>179          </li>180          <li>181              182          </li>183    <li id="cpython-language-and-version">184      <a href="../index.html">3.15.0a6 Documentation</a> &#187;185    </li>186 187          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>188          <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>189          <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>190        <li class="nav-item nav-item-this"><a href="">Runners</a></li>191                <li class="right">192                    193 194    <div class="inline-search" role="search">195        <form class="inline-search" action="../search.html" method="get">196          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">197          <input type="submit" value="Go">198        </form>199    </div>200                     |201                </li>202            <li class="right">203<label class="theme-selector-label">204    Theme205    <select class="theme-selector" oninput="activateTheme(this.value)">206        <option value="auto" selected>Auto</option>207        <option value="light">Light</option>208        <option value="dark">Dark</option>209    </select>210</label> |</li>211            212      </ul>213    </div>    214 215    <div class="document">216      <div class="documentwrapper">217        <div class="bodywrapper">218          <div class="body" role="main">219            220  <section id="runners">221<h1>Runners<a class="headerlink" href="#runners" title="Link to this heading">¶</a></h1>222<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/asyncio/runners.py">Lib/asyncio/runners.py</a></p>223<p>This section outlines high-level asyncio primitives to run asyncio code.</p>224<p>They are built on top of an <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">event loop</span></a> with the aim225to simplify async code usage for common wide-spread scenarios.</p>226<nav class="contents local" id="contents">227<ul class="simple">228<li><p><a class="reference internal" href="#running-an-asyncio-program" id="id1">Running an asyncio Program</a></p></li>229<li><p><a class="reference internal" href="#runner-context-manager" id="id2">Runner context manager</a></p></li>230<li><p><a class="reference internal" href="#handling-keyboard-interruption" id="id3">Handling Keyboard Interruption</a></p></li>231</ul>232</nav>233<section id="running-an-asyncio-program">234<h2><a class="toc-backref" href="#id1" role="doc-backlink">Running an asyncio Program</a><a class="headerlink" href="#running-an-asyncio-program" title="Link to this heading">¶</a></h2>235<dl class="py function">236<dt class="sig sig-object py" id="asyncio.run">237<span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">run</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">debug</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">loop_factory</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.run" title="Link to this definition">¶</a></dt>238<dd><p>Execute <em>coro</em> in an asyncio event loop and return the result.</p>239<p>The argument can be any awaitable object.</p>240<p>This function runs the awaitable, taking care of managing the241asyncio event loop, <em>finalizing asynchronous generators</em>, and242closing the executor.</p>243<p>This function cannot be called when another asyncio event loop is244running in the same thread.</p>245<p>If <em>debug</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the event loop will be run in debug mode. <code class="docutils literal notranslate"><span class="pre">False</span></code> disables246debug mode explicitly. <code class="docutils literal notranslate"><span class="pre">None</span></code> is used to respect the global247<a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">Debug Mode</span></a> settings.</p>248<p>If <em>loop_factory</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is used to create a new event loop;249otherwise <a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.new_event_loop()</span></code></a> is used. The loop is closed at the end.250This function should be used as a main entry point for asyncio programs,251and should ideally only be called once. It is recommended to use252<em>loop_factory</em> to configure the event loop instead of policies.253Passing <a class="reference internal" href="asyncio-eventloop.html#asyncio.EventLoop" title="asyncio.EventLoop"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.EventLoop</span></code></a> allows running asyncio without the254policy system.</p>255<p>The executor is given a timeout duration of 5 minutes to shutdown.256If the executor hasn’t finished within that duration, a warning is257emitted and the executor is closed.</p>258<p>Example:</p>259<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>260    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>261    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>262 263<span class="n">asyncio</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>264</pre></div>265</div>266<div class="versionadded">267<p><span class="versionmodified added">Added in version 3.7.</span></p>268</div>269<div class="versionchanged">270<p><span class="versionmodified changed">Changed in version 3.9: </span>Updated to use <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.shutdown_default_executor" title="asyncio.loop.shutdown_default_executor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.shutdown_default_executor()</span></code></a>.</p>271</div>272<div class="versionchanged">273<p><span class="versionmodified changed">Changed in version 3.10: </span><em>debug</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> by default to respect the global debug mode settings.</p>274</div>275<div class="versionchanged">276<p><span class="versionmodified changed">Changed in version 3.12: </span>Added <em>loop_factory</em> parameter.</p>277</div>278<div class="versionchanged">279<p><span class="versionmodified changed">Changed in version 3.14: </span><em>coro</em> can be any awaitable object.</p>280</div>281<div class="admonition note">282<p class="admonition-title">Note</p>283<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> policy system is deprecated and will be removed284in Python 3.16; from there on, an explicit <em>loop_factory</em> is needed285to configure the event loop.</p>286</div>287</dd></dl>288 289</section>290<section id="runner-context-manager">291<h2><a class="toc-backref" href="#id2" role="doc-backlink">Runner context manager</a><a class="headerlink" href="#runner-context-manager" title="Link to this heading">¶</a></h2>292<dl class="py class">293<dt class="sig sig-object py" id="asyncio.Runner">294<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Runner</span></span><span class="sig-paren">(</span><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">debug</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">loop_factory</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.Runner" title="Link to this definition">¶</a></dt>295<dd><p>A context manager that simplifies <em>multiple</em> async function calls in the same296context.</p>297<p>Sometimes several top-level async functions should be called in the same <a class="reference internal" href="asyncio-eventloop.html#asyncio-event-loop"><span class="std std-ref">event298loop</span></a> and <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>.</p>299<p>If <em>debug</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the event loop will be run in debug mode. <code class="docutils literal notranslate"><span class="pre">False</span></code> disables300debug mode explicitly. <code class="docutils literal notranslate"><span class="pre">None</span></code> is used to respect the global301<a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">Debug Mode</span></a> settings.</p>302<p><em>loop_factory</em> could be used for overriding the loop creation.303It is the responsibility of the <em>loop_factory</em> to set the created loop as the304current one. By default <a class="reference internal" href="asyncio-eventloop.html#asyncio.new_event_loop" title="asyncio.new_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.new_event_loop()</span></code></a> is used and set as305current event loop with <a class="reference internal" href="asyncio-eventloop.html#asyncio.set_event_loop" title="asyncio.set_event_loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.set_event_loop()</span></code></a> if <em>loop_factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>306<p>Basically, <a class="reference internal" href="#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> example can be rewritten with the runner usage:</p>307<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span><span class="w"> </span><span class="nf">main</span><span class="p">():</span>308    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>309    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>310 311<span class="k">with</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Runner</span><span class="p">()</span> <span class="k">as</span> <span class="n">runner</span><span class="p">:</span>312    <span class="n">runner</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>313</pre></div>314</div>315<div class="versionadded">316<p><span class="versionmodified added">Added in version 3.11.</span></p>317</div>318<dl class="py method">319<dt class="sig sig-object py" id="asyncio.Runner.run">320<span class="sig-name descname"><span class="pre">run</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">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.Runner.run" title="Link to this definition">¶</a></dt>321<dd><p>Execute <em>coro</em> in the embedded event loop.</p>322<p>The argument can be any awaitable object.</p>323<p>If the argument is a coroutine, it is wrapped in a Task.</p>324<p>An optional keyword-only <em>context</em> argument allows specifying a325custom <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 code to run in.326The runner’s default context is used if context is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>327<p>Returns the awaitable’s result or raises an exception.</p>328<p>This function cannot be called when another asyncio event loop is329running in the same thread.</p>330<div class="versionchanged">331<p><span class="versionmodified changed">Changed in version 3.14: </span><em>coro</em> can be any awaitable object.</p>332</div>333</dd></dl>334 335<dl class="py method">336<dt class="sig sig-object py" id="asyncio.Runner.close">337<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.Runner.close" title="Link to this definition">¶</a></dt>338<dd><p>Close the runner.</p>339<p>Finalize asynchronous generators, shutdown default executor, close the event loop340and release embedded <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>.</p>341</dd></dl>342 343<dl class="py method">344<dt class="sig sig-object py" id="asyncio.Runner.get_loop">345<span class="sig-name descname"><span class="pre">get_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Runner.get_loop" title="Link to this definition">¶</a></dt>346<dd><p>Return the event loop associated with the runner instance.</p>347</dd></dl>348 349<div class="admonition note">350<p class="admonition-title">Note</p>351<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Runner</span></code> uses the lazy initialization strategy, its constructor doesn’t352initialize underlying low-level structures.</p>353<p>Embedded <em>loop</em> and <em>context</em> are created at the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> body entering354or the first call of <a class="reference internal" href="#asyncio.run" title="asyncio.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> or <a class="reference internal" href="#asyncio.Runner.get_loop" title="asyncio.Runner.get_loop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_loop()</span></code></a>.</p>355</div>356</dd></dl>357 358</section>359<section id="handling-keyboard-interruption">360<h2><a class="toc-backref" href="#id3" role="doc-backlink">Handling Keyboard Interruption</a><a class="headerlink" href="#handling-keyboard-interruption" title="Link to this heading">¶</a></h2>361<div class="versionadded">362<p><span class="versionmodified added">Added in version 3.11.</span></p>363</div>364<p>When <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> is raised by <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>, <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>365exception is raised in the main thread by default. However this doesn’t work with366<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> because it can interrupt asyncio internals and can hang the program from367exiting.</p>368<p>To mitigate this issue, <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> handles <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> as follows:</p>369<ol class="arabic simple">370<li><p><a class="reference internal" href="#asyncio.Runner.run" title="asyncio.Runner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Runner.run()</span></code></a> installs a custom <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> handler before371any user code is executed and removes it when exiting from the function.</p></li>372<li><p>The <a class="reference internal" href="#asyncio.Runner" title="asyncio.Runner"><code class="xref py py-class docutils literal notranslate"><span class="pre">Runner</span></code></a> creates the main task for the passed coroutine for its373execution.</p></li>374<li><p>When <a class="reference internal" href="signal.html#signal.SIGINT" title="signal.SIGINT"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code></a> is raised by <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>, the custom signal handler375cancels the main task by calling <a class="reference internal" href="asyncio-task.html#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Task.cancel()</span></code></a> which raises376<a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.CancelledError</span></code></a> inside the main task.  This causes the Python stack377to unwind, <code class="docutils literal notranslate"><span class="pre">try/except</span></code> and <code class="docutils literal notranslate"><span class="pre">try/finally</span></code> blocks can be used for resource378cleanup.  After the main task is cancelled, <a class="reference internal" href="#asyncio.Runner.run" title="asyncio.Runner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Runner.run()</span></code></a> raises379<a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>.</p></li>380<li><p>A user could write a tight loop which cannot be interrupted by381<a class="reference internal" href="asyncio-task.html#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Task.cancel()</span></code></a>, in which case the second following <kbd class="kbd docutils literal notranslate">Ctrl</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd>382immediately raises the <a class="reference internal" href="exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> without cancelling the main task.</p></li>383</ol>384</section>385</section>386 387 388            <div class="clearer"></div>389          </div>390        </div>391      </div>392      <div class="sphinxsidebar" role="navigation" aria-label="Main">393        <div class="sphinxsidebarwrapper">394  <div>395    <h3><a href="../contents.html">Table of Contents</a></h3>396    <ul>397<li><a class="reference internal" href="#">Runners</a><ul>398<li><a class="reference internal" href="#running-an-asyncio-program">Running an asyncio Program</a></li>399<li><a class="reference internal" href="#runner-context-manager">Runner context manager</a></li>400<li><a class="reference internal" href="#handling-keyboard-interruption">Handling Keyboard Interruption</a></li>401</ul>402</li>403</ul>404 405  </div>406  <div>407    <h4>Previous topic</h4>408    <p class="topless"><a href="asyncio.html"409                          title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a></p>410  </div>411  <div>412    <h4>Next topic</h4>413    <p class="topless"><a href="asyncio-task.html"414                          title="next chapter">Coroutines and Tasks</a></p>415  </div>416  <script>417    document.addEventListener('DOMContentLoaded', () => {418        const title = document.querySelector('meta[property="og:title"]').content;419        const elements = document.querySelectorAll('.improvepage');420        const pageurl = window.location.href.split('?')[0];421        elements.forEach(element => {422            const url = new URL(element.href.split('?')[0].replace("-nojs", ""));423            url.searchParams.set('pagetitle', title);424            url.searchParams.set('pageurl', pageurl);425            url.searchParams.set('pagesource', "library/asyncio-runner.rst");426            element.href = url.toString();427        });428    });429  </script>430  <div role="note" aria-label="source link">431    <h3>This page</h3>432    <ul class="this-page-menu">433      <li><a href="../bugs.html">Report a bug</a></li>434      <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>435      <li>436        <a href="https://github.com/python/cpython/blob/main/Doc/library/asyncio-runner.rst?plain=1"437            rel="nofollow">Show source438        </a>439      </li>440      441    </ul>442  </div>443        </div>444<div id="sidebarbutton" title="Collapse sidebar">445<span>«</span>446</div>447 448      </div>449      <div class="clearer"></div>450    </div>  451    <div class="related" role="navigation" aria-label="Related">452      <h3>Navigation</h3>453      <ul>454        <li class="right" style="margin-right: 10px">455          <a href="../genindex.html" title="General Index"456             >index</a></li>457        <li class="right" >458          <a href="../py-modindex.html" title="Python Module Index"459             >modules</a> |</li>460        <li class="right" >461          <a href="asyncio-task.html" title="Coroutines and Tasks"462             >next</a> |</li>463        <li class="right" >464          <a href="asyncio.html" title="asyncio — Asynchronous I/O"465             >previous</a> |</li>466 467          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>468          <li><a href="https://www.python.org/">Python</a> &#187;</li>469          <li class="switchers">470            <div class="language_switcher_placeholder"></div>471            <div class="version_switcher_placeholder"></div>472          </li>473          <li>474              475          </li>476    <li id="cpython-language-and-version">477      <a href="../index.html">3.15.0a6 Documentation</a> &#187;478    </li>479 480          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>481          <li class="nav-item nav-item-2"><a href="ipc.html" >Networking and Interprocess Communication</a> &#187;</li>482          <li class="nav-item nav-item-3"><a href="asyncio.html" ><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O</a> &#187;</li>483        <li class="nav-item nav-item-this"><a href="">Runners</a></li>484                <li class="right">485                    486 487    <div class="inline-search" role="search">488        <form class="inline-search" action="../search.html" method="get">489          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">490          <input type="submit" value="Go">491        </form>492    </div>493                     |494                </li>495            <li class="right">496<label class="theme-selector-label">497    Theme498    <select class="theme-selector" oninput="activateTheme(this.value)">499        <option value="auto" selected>Auto</option>500        <option value="light">Light</option>501        <option value="dark">Dark</option>502    </select>503</label> |</li>504            505      </ul>506    </div>  507    <div class="footer">508    &copy; <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.509    <br>510    This page is licensed under the Python Software Foundation License Version 2.511    <br>512    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.513    <br>514    515      See <a href="/license.html">History and License</a> for more information.<br>516    517    518    <br>519 520    The Python Software Foundation is a non-profit corporation.521<a href="https://www.python.org/psf/donations/">Please donate.</a>522<br>523    <br>524      Last updated on Mar 10, 2026 (08:58 UTC).525    526      <a href="/bugs.html">Found a bug</a>?527    528    <br>529 530    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.531    </div>532 533  </body>534</html>