Files
hustoj/web/python-docs/library/asyncio-eventloop.html
2025-03-09 17:10:56 +08:00

1523 lines
172 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
<head>
<meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<title>事件循环 &#8212; Python 3.8.20 文档</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script src="../_static/translations.js"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.8.20 文档 中搜索"
href="../_static/opensearch.xml"/>
<link rel="author" title="关于这些文档" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜索" href="../search.html" />
<link rel="copyright" title="版权所有" href="../copyright.html" />
<link rel="next" title="Futures" href="asyncio-future.html" />
<link rel="prev" title="异常" href="asyncio-exceptions.html" />
<link rel="canonical" href="https://docs.python.org/3/library/asyncio-eventloop.html" />
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/menu.js"></script>
</head>
<body>
<div class="mobile-nav">
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
<label for="menuToggler" class="toggler__label">
<span></span>
</label>
<nav class="nav-content" role="navigation">
<a href="https://www.python.org/" class="nav-logo">
<img src="../_static/py.svg" alt="Logo"/>
</a>
<div class="version_switcher_placeholder"></div>
<form role="search" class="search" action="../search.html" method="get">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
<path fill-rule="nonzero"
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" fill="#444"></path>
</svg>
<input type="text" name="q" aria-label="快速搜索"/>
<input type="submit" value="转向"/>
</form>
</nav>
<div class="menu-wrapper">
<nav class="menu" role="navigation" aria-label="main navigation">
<div class="language_switcher_placeholder"></div>
<h3><a href="../contents.html">目录</a></h3>
<ul>
<li><a class="reference internal" href="#">事件循环</a><ul>
<li><a class="reference internal" href="#event-loop-methods">事件循环方法集</a><ul>
<li><a class="reference internal" href="#running-and-stopping-the-loop">运行和停止循环</a></li>
<li><a class="reference internal" href="#scheduling-callbacks">安排回调</a></li>
<li><a class="reference internal" href="#scheduling-delayed-callbacks">调度延迟回调</a></li>
<li><a class="reference internal" href="#creating-futures-and-tasks">创建 Future 和 Task</a></li>
<li><a class="reference internal" href="#opening-network-connections">打开网络连接</a></li>
<li><a class="reference internal" href="#creating-network-servers">创建网络服务</a></li>
<li><a class="reference internal" href="#transferring-files">传输文件</a></li>
<li><a class="reference internal" href="#tls-upgrade">TLS 升级</a></li>
<li><a class="reference internal" href="#watching-file-descriptors">监控文件描述符</a></li>
<li><a class="reference internal" href="#working-with-socket-objects-directly">直接使用 socket 对象</a></li>
<li><a class="reference internal" href="#dns">DNS</a></li>
<li><a class="reference internal" href="#working-with-pipes">使用管道</a></li>
<li><a class="reference internal" href="#unix-signals">Unix 信号</a></li>
<li><a class="reference internal" href="#executing-code-in-thread-or-process-pools">在线程或者进程池中执行代码。</a></li>
<li><a class="reference internal" href="#error-handling-api">错误处理API</a></li>
<li><a class="reference internal" href="#enabling-debug-mode">开启调试模式</a></li>
<li><a class="reference internal" href="#running-subprocesses">运行子进程</a></li>
</ul>
</li>
<li><a class="reference internal" href="#callback-handles">回调处理</a></li>
<li><a class="reference internal" href="#server-objects">Server 对象</a></li>
<li><a class="reference internal" href="#event-loop-implementations">事件循环实现</a></li>
<li><a class="reference internal" href="#examples">例子</a><ul>
<li><a class="reference internal" href="#hello-world-with-call-soon">call_soon() 的 Hello World 示例。</a></li>
<li><a class="reference internal" href="#display-the-current-date-with-call-later">使用 call_later() 来展示当前的日期</a></li>
<li><a class="reference internal" href="#watch-a-file-descriptor-for-read-events">监控一个文件描述符的读事件</a></li>
<li><a class="reference internal" href="#set-signal-handlers-for-sigint-and-sigterm">为SIGINT和SIGTERM设置信号处理器</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="asyncio-exceptions.html"
title="上一章">异常</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="asyncio-future.html"
title="下一章">Futures</a></p>
<div role="note" aria-label="source link">
<h3>本页</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">报告 Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.8/Doc/library/asyncio-eventloop.rst"
rel="nofollow">显示源代码
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div id="outdated-warning" style="padding: .5em; text-align: center; background-color: #FFBABA; color: #6A0E0E;">
这个文档所针对的是一个已不再受支持的 Python 旧版本。
你应当升级版本,并阅读
<a href="/3/library/asyncio-eventloop.html"> Python 当前稳定版本的文档</a>.
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>导航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="总目录"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模块索引"
>模块</a> |</li>
<li class="right" >
<a href="asyncio-future.html" title="Futures"
accesskey="N">下一页</a> |</li>
<li class="right" >
<a href="asyncio-exceptions.html" title="异常"
accesskey="P">上一页</a> |</li>
<li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.8.20 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
<li class="nav-item nav-item-2"><a href="ipc.html" >网络和进程间通信</a> &#187;</li>
<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> --- 异步 I/O</a> &#187;</li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
<input type="submit" value="转向" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<section id="event-loop">
<h1>事件循环<a class="headerlink" href="#event-loop" title="永久链接至标题"></a></h1>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.8/Lib/asyncio/events.py">Lib/asyncio/events.py</a>, <a class="reference external" href="https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a></p>
<hr class="docutils" />
<p class="rubric">前言</p>
<p>事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调,执行网络 IO 操作,以及运行子进程。</p>
<p>应用开发者通常应当使用高层级的 asyncio 函数,例如 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a>,应当很少有必要引用循环对象或调用其方法。 本节所针对的主要是低层级代码、库和框架的编写者,他们需要更细致地控制事件循环行为。</p>
<p class="rubric">获取事件循环</p>
<p>以下低层级函数可被用于获取、设置或创建事件循环:</p>
<dl class="function">
<dt id="asyncio.get_running_loop">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">get_running_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_running_loop" title="永久链接至目标"></a></dt>
<dd><p>返回当前 OS 线程中正在运行的事件循环。</p>
<p>如果没有正在运行的事件循环则会引发 <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>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="function">
<dt id="asyncio.get_event_loop">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">get_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.get_event_loop" title="永久链接至目标"></a></dt>
<dd><p>获取当前事件循环。</p>
<p>如果当前 OS 线程没有设置当前事件循环,该 OS 线程为主线程,并且 <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> 还没有被调用,则 asyncio 将创建一个新的事件循环并将其设为当前事件循环。</p>
<p>由于此函数具有相当复杂的行为(特别是在使用了自定义事件循环策略的时候),更推荐在协程和回调中使用 <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> 函数而非 <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></p>
<p>应该考虑使用 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> 函数而非使用低层级函数来手动创建和关闭事件循环。</p>
</dd></dl>
<dl class="function">
<dt id="asyncio.set_event_loop">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">set_event_loop</code><span class="sig-paren">(</span><em class="sig-param">loop</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.set_event_loop" title="永久链接至目标"></a></dt>
<dd><p><em>loop</em> 设置为当前 OS 线程的当前事件循环。</p>
</dd></dl>
<dl class="function">
<dt id="asyncio.new_event_loop">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">new_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.new_event_loop" title="永久链接至目标"></a></dt>
<dd><p>创建一个新的事件循环。</p>
</dd></dl>
<p>请注意 <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> 以及 <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> 函数的行为可以通过 <a class="reference internal" href="asyncio-policy.html#asyncio-policies"><span class="std std-ref">设置自定义事件循环策略</span></a> 来改变。</p>
<p class="rubric">目录</p>
<p>本文档包含下列小节:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#event-loop-methods">事件循环方法集</a> 章节是事件循环APIs的参考文档</p></li>
<li><p><a class="reference internal" href="#callback-handles">回调处理</a> 章节是从调度方法 例如 <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><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> 中返回 <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> 和 <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> 实例的文档。</p></li>
<li><p><a class="reference internal" href="#server-objects">Server Objects</a> 章节记录了从事件循环方法返回的类型,比如 <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>
<li><p><a class="reference internal" href="#event-loop-implementations">Event Loop Implementations</a> 章节记录了 <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><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></li>
<li><p><a class="reference internal" href="#examples">Examples</a> 章节展示了如何使用某些事件循环API。</p></li>
</ul>
<section id="event-loop-methods">
<span id="asyncio-event-loop"></span><h2>事件循环方法集<a class="headerlink" href="#event-loop-methods" title="永久链接至标题"></a></h2>
<p>事件循环有下列 <strong>低级</strong> APIs</p>
<div class="contents local topic" id="id1">
<ul class="simple">
<li><p><a class="reference internal" href="#running-and-stopping-the-loop" id="id2">运行和停止循环</a></p></li>
<li><p><a class="reference internal" href="#scheduling-callbacks" id="id3">安排回调</a></p></li>
<li><p><a class="reference internal" href="#scheduling-delayed-callbacks" id="id4">调度延迟回调</a></p></li>
<li><p><a class="reference internal" href="#creating-futures-and-tasks" id="id5">创建 Future 和 Task</a></p></li>
<li><p><a class="reference internal" href="#opening-network-connections" id="id6">打开网络连接</a></p></li>
<li><p><a class="reference internal" href="#creating-network-servers" id="id7">创建网络服务</a></p></li>
<li><p><a class="reference internal" href="#transferring-files" id="id8">传输文件</a></p></li>
<li><p><a class="reference internal" href="#tls-upgrade" id="id9">TLS 升级</a></p></li>
<li><p><a class="reference internal" href="#watching-file-descriptors" id="id10">监控文件描述符</a></p></li>
<li><p><a class="reference internal" href="#working-with-socket-objects-directly" id="id11">直接使用 socket 对象</a></p></li>
<li><p><a class="reference internal" href="#dns" id="id12">DNS</a></p></li>
<li><p><a class="reference internal" href="#working-with-pipes" id="id13">使用管道</a></p></li>
<li><p><a class="reference internal" href="#unix-signals" id="id14">Unix 信号</a></p></li>
<li><p><a class="reference internal" href="#executing-code-in-thread-or-process-pools" id="id15">在线程或者进程池中执行代码。</a></p></li>
<li><p><a class="reference internal" href="#error-handling-api" id="id16">错误处理API</a></p></li>
<li><p><a class="reference internal" href="#enabling-debug-mode" id="id17">开启调试模式</a></p></li>
<li><p><a class="reference internal" href="#running-subprocesses" id="id18">运行子进程</a></p></li>
</ul>
</div>
<section id="running-and-stopping-the-loop">
<h3><a class="toc-backref" href="#id2">运行和停止循环</a><a class="headerlink" href="#running-and-stopping-the-loop" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.run_until_complete">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">run_until_complete</code><span class="sig-paren">(</span><em class="sig-param">future</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_until_complete" title="永久链接至目标"></a></dt>
<dd><p>运行直到 <em>future</em> ( <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> 的实例 ) 被完成。</p>
<p>如果参数是 <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">coroutine object</span></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>
<p>返回 Future 的结果 或者引发相关异常。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.run_forever">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">run_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_forever" title="永久链接至目标"></a></dt>
<dd><p>运行事件循环直到 <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> 被调用。</p>
<p>如果 <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> 在调用 <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a> 之前被调用,循环将轮询一次 I/O 选择器并设置超时为零,再运行所有已加入计划任务的回调来响应 I/O 事件(以及已加入计划任务的事件),然后退出。</p>
<p>如果 <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><a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a> 运行期间被调用,循环将运行当前批次的回调然后退出。 请注意在此情况下由回调加入计划任务的新回调将不会运行;它们将会在下次 <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_forever()</span></code></a><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> 被调用时运行。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.stop">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.stop" title="永久链接至目标"></a></dt>
<dd><p>停止事件循环。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.is_running">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">is_running</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_running" title="永久链接至目标"></a></dt>
<dd><p>返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> 如果事件循环当前正在运行。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.is_closed">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">is_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.is_closed" title="永久链接至目标"></a></dt>
<dd><p>如果事件循环已经被关闭,返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.close">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.close" title="永久链接至目标"></a></dt>
<dd><p>关闭事件循环。</p>
<p>当这个函数被调用的时候循环必须处于非运行状态。pending状态的回调将被丢弃。</p>
<p>此方法清除所有的队列并立即关闭执行器,不会等待执行器完成。</p>
<p>这个方法是幂等的和不可逆的。事件循环关闭后,不应调用其他方法。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.shutdown_asyncgens">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">shutdown_asyncgens</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.shutdown_asyncgens" title="永久链接至目标"></a></dt>
<dd><p>安排所有当前打开的 <a class="reference internal" href="../glossary.html#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> 对象通过 <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> 调用来关闭。 在调用此方法后,如果有新的异步生成器被迭代事件循环将会发出警告。 这应当被用来可靠地完成所有已加入计划任务的异步生成器。</p>
<p>请注意当使用 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a> 时不必调用此函数。</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
<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>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.6 新版功能.</span></p>
</div>
</dd></dl>
</section>
<section id="scheduling-callbacks">
<h3><a class="toc-backref" href="#id3">安排回调</a><a class="headerlink" href="#scheduling-callbacks" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.call_soon">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">call_soon</code><span class="sig-paren">(</span><em class="sig-param">callback</em>, <em class="sig-param">*args</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon" title="永久链接至目标"></a></dt>
<dd><p>安排 <em>callback</em> <a class="reference internal" href="../glossary.html#term-callback"><span class="xref std std-term">callback</span></a> 在事件循环的下一次迭代时附带 <em>args</em> 参数被调用。</p>
<p>回调按其注册顺序被调用。每个回调仅被调用一次。</p>
<p>可选键值类的参数 <em>context</em> 允许 <em>callback</em> 运行在一个指定的自定义 <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> 对象中。如果没有提供 <em>context</em> ,则使用当前上下文。</p>
<p>返回一个能用来取消回调的 <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> 实例。</p>
<p>这个方法不是线程安全的。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.call_soon_threadsafe">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">call_soon_threadsafe</code><span class="sig-paren">(</span><em class="sig-param">callback</em>, <em class="sig-param">*args</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_soon_threadsafe" title="永久链接至目标"></a></dt>
<dd><p><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> 的线程安全变体。必须被用于安排 <em>来自其他线程</em> 的回调。</p>
<p>参见 <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a> 部分的文档。</p>
</dd></dl>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>加入键值类形参 <em>context</em>。请参阅 <span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="admonition note" id="asyncio-pass-keywords">
<p class="admonition-title">注解</p>
<p>大多数 <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> 的调度函数不让传递关键字参数。为此,请使用 <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>
<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>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span>
<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>
</pre></div>
</div>
<p>使用 partial 对象通常比使用lambda更方便asyncio 在调试和错误消息中能更好的呈现 partial 对象。</p>
</div>
</section>
<section id="scheduling-delayed-callbacks">
<span id="asyncio-delayed-calls"></span><h3><a class="toc-backref" href="#id4">调度延迟回调</a><a class="headerlink" href="#scheduling-delayed-callbacks" title="永久链接至标题"></a></h3>
<p>事件循环提供安排调度函数在将来某个时刻调用的机制。事件循环使用单调时钟来跟踪时间。</p>
<dl class="method">
<dt id="asyncio.loop.call_later">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">call_later</code><span class="sig-paren">(</span><em class="sig-param">delay</em>, <em class="sig-param">callback</em>, <em class="sig-param">*args</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_later" title="永久链接至目标"></a></dt>
<dd><p>安排 <em>callback</em> 在给定的 <em>delay</em> 秒(可以是 int 或者 float后被调用。</p>
<p>返回一个 <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> 实例,该实例能用于取消回调。</p>
<p><em>callback</em> 只被调用一次。如果两个回调被安排在同样的时间点,执行顺序未限定。</p>
<p>可选的位置参数 <em>args</em> 在被调用的时候传递给 <em>callback</em>  。 如果你想把关键字参数传递给 <em>callback</em> ,请使用 <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>
<p>可选键值类的参数 <em>context</em> 允许 <em>callback</em> 运行在一个指定的自定义 <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> 对象中。如果没有提供 <em>context</em> ,则使用当前上下文。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>加入键值类形参 <em>context</em>。请参阅 <span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版更改: </span>在 Python 3.7 和更早版本的默认事件循环实现中, <em>delay</em> 不能超过一天。 这在 Python 3.8 中已被修复。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.call_at">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">call_at</code><span class="sig-paren">(</span><em class="sig-param">when</em>, <em class="sig-param">callback</em>, <em class="sig-param">*args</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_at" title="永久链接至目标"></a></dt>
<dd><p>安排 <em>callback</em> 在给定的绝对时间戳 <em>when</em> (int 或 float) 被调用,使用与 <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>
<p>本方法的行为和 <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>
<p>返回一个 <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> 实例,该实例能用于取消回调。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>加入键值类形参 <em>context</em>。请参阅 <span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版更改: </span>在 Python 3.7 和更早版本的默认事件循环实现中,<em>when</em> 和当前时间相差不能超过一天。 在这 Python 3.8 中已被修复。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.time">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">time</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.time" title="永久链接至目标"></a></dt>
<dd><p>根据时间循环内部的单调时钟,返回当前时间为一个 <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> 值。</p>
</dd></dl>
<div class="admonition note">
<p class="admonition-title">注解</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版更改: </span>在 Python 3.7 和更早版本中超时 (相对的 <em>delay</em> 或绝对的 <em>when</em>) 不能超过一天。 这在 Python 3.8 中已被修复。</p>
</div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><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> 函数。</p>
</div>
</section>
<section id="creating-futures-and-tasks">
<h3><a class="toc-backref" href="#id5">创建 Future 和 Task</a><a class="headerlink" href="#creating-futures-and-tasks" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.create_future">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_future</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_future" title="永久链接至目标"></a></dt>
<dd><p>创建一个附加到事件循环中的 <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> 对象。</p>
<p>这是在asyncio中创建Futures的首选方式。这让第三方事件循环可以提供Future 对象的替代实现(更好的性能或者功能)。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5.2 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.create_task">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_task</code><span class="sig-paren">(</span><em class="sig-param">coro</em>, <em class="sig-param">*</em>, <em class="sig-param">name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_task" title="永久链接至目标"></a></dt>
<dd><p>安排一个 <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">协程</span></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> 对象。</p>
<p>第三方的事件循环可以使用它们自己的 <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> 子类来满足互操作性。这种情况下结果类型是一个 <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> 的子类。</p>
<p>如果提供了 <em>name</em> 参数且不为 <code class="docutils literal notranslate"><span class="pre">None</span></code>,它会使用 <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>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">name</span></code> 形参。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.set_task_factory">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">set_task_factory</code><span class="sig-paren">(</span><em class="sig-param">factory</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_task_factory" title="永久链接至目标"></a></dt>
<dd><p>设置一个任务工厂,它将由 <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>
<p>如果 <em>factory</em><code class="docutils literal notranslate"><span class="pre">None</span></code> 则将设置默认的任务工厂。 在其他情况下,<em>factory</em> 必须为一个 <em>可调用对象</em> 且签名匹配 <code class="docutils literal notranslate"><span class="pre">(loop,</span> <span class="pre">coro)</span></code>,其中 <em>loop</em> 是对活动事件循环的引用,而 <em>coro</em> 是一个协程对象。 该可调用对象必须返回一个兼容 <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> 的对象。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.get_task_factory">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">get_task_factory</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_task_factory" title="永久链接至目标"></a></dt>
<dd><p>返回一个任务工厂,或者如果是使用默认值则返回 <code class="docutils literal notranslate"><span class="pre">None</span></code></p>
</dd></dl>
</section>
<section id="opening-network-connections">
<h3><a class="toc-backref" href="#id6">打开网络连接</a><a class="headerlink" href="#opening-network-connections" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.create_connection">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_connection</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">host=None</em>, <em class="sig-param">port=None</em>, <em class="sig-param">*</em>, <em class="sig-param">ssl=None</em>, <em class="sig-param">family=0</em>, <em class="sig-param">proto=0</em>, <em class="sig-param">flags=0</em>, <em class="sig-param">sock=None</em>, <em class="sig-param">local_addr=None</em>, <em class="sig-param">server_hostname=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em>, <em class="sig-param">happy_eyeballs_delay=None</em>, <em class="sig-param">interleave=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_connection" title="永久链接至目标"></a></dt>
<dd><p>打开一个流式传输连接,连接到由 <em>host</em><em>port</em> 指定的地址。</p>
<p>套接字族可以是 <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a><a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>,具体取决于 <em>host</em> (或 <em>family</em> 参数,如果有提供的话)。</p>
<p>套接字类型将为 <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a></p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio 协议</span></a> 实现的可调用对象。</p>
<p>这个方法会尝试在后台创建连接。当创建成功,返回 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 组合。</p>
<p>底层操作的大致的执行顺序是这样的:</p>
<ol class="arabic simple">
<li><p>创建连接并为其创建一个 <a class="reference internal" href="asyncio-protocol.html#asyncio-transport"><span class="std std-ref">传输</span></a></p></li>
<li><p>不带参数地调用 <em>protocol_factory</em> 并预期返回一个 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">协议</span></a> 实例。</p></li>
<li><p>协议实例通过调用其 <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> 方法与传输进行配对。</p></li>
<li><p>成功时返回一个 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 元组。</p></li>
</ol>
<p>创建的传输是一个具体实现相关的双向流。</p>
<p>其他参数:</p>
<ul>
<li><p><em>ssl</em>: 如果给定该参数且不为假值,则会创建一个 SSL/TLS 传输(默认创建一个纯 TCP 传输)。 如果 <em>ssl</em> 是一个 <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> 对象,则会使用此上下文来创建传输对象;如果 <em>ssl</em><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 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> 返回的默认上下文。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="ssl.html#ssl-security"><span class="std std-ref">SSL/TLS security considerations</span></a></p>
</div>
</li>
<li><p><em>server_hostname</em> 设置或覆盖目标服务器的证书将要匹配的主机名。 应当只在 <em>ssl</em> 不为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 时传入。 默认情况下会使用 <em>host</em> 参数的值。 如果 <em>host</em> 为空那就没有默认值,你必须为 <em>server_hostname</em> 传入一个值。 如果 <em>server_hostname</em> 为空字符串,则主机名匹配会被禁用(这是一个严重的安全风险,使得潜在的中间人攻击成为可能)。</p></li>
<li><p><em>family</em>, <em>proto</em>, <em>flags</em> 是可选的地址族、协议和标志,它们会被传递给 getaddrinfo() 来对 <em>host</em> 进行解析。如果要指定的话,这些都应该是来自于 <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> 模块的对应常量。</p></li>
<li><p>如果给出 <em>happy_eyeballs_delay</em>,它将为此链接启用 Happy Eyeballs。 该函数应当为一个表示在开始下一个并行尝试之前要等待连接尝试完成的秒数的浮点数。 这也就是在 <span class="target" id="index-15"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc8305.html"><strong>RFC 8305</strong></a> 中定义的 &quot;连接尝试延迟&quot;。 该 RFC 所推荐的合理默认值为 <code class="docutils literal notranslate"><span class="pre">0.25</span></code> (250 毫秒)。</p></li>
<li><p><em>interleave</em> 控制当主机名解析为多个 IP 地址时的地址重排序。 如果该参数为 <code class="docutils literal notranslate"><span class="pre">0</span></code> 或未指定,则不会进行重排序,这些地址会按 <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> 所返回的顺序进行尝试。 如果指定了一个正整数,这些地址会按地址族交错排列,而指定的整数会被解读为 <span class="target" id="index-16"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc8305.html"><strong>RFC 8305</strong></a> 所定义的 &quot;首个地址族计数&quot;。 如果 <em>happy_eyeballs_delay</em> 未指定则默认值为 <code class="docutils literal notranslate"><span class="pre">0</span></code>,否则为 <code class="docutils literal notranslate"><span class="pre">1</span></code></p></li>
<li><p>如果给出 <em>sock</em>,它应当是一个已存在、已连接并将被传输所使用的 <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> 对象。 如果给出了 <em>sock</em>,则 <em>host</em>, <em>port</em>, <em>family</em>, <em>proto</em>, <em>flags</em>, <em>happy_eyeballs_delay</em>, <em>interleave</em><em>local_addr</em> 都不应当被指定。</p></li>
<li><p>如果给出 <em>local_addr</em>,它应当是一个用来在本地绑定套接字的 <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> 元组。 <em>local_host</em><em>local_port</em> 会使用 <code class="docutils literal notranslate"><span class="pre">getaddrinfo()</span></code> 来查找,这与 <em>host</em><em>port</em> 类似。</p></li>
<li><p><em>ssl_handshake_timeout</em> 是(用于 TLS 连接的)在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 则使用 (默认的) <code class="docutils literal notranslate"><span class="pre">60.0</span></code></p></li>
</ul>
<div class="versionadded">
<p><span class="versionmodified added">3.8 新版功能: </span>增加了 <em>happy_eyeballs_delay</em><em>interleave</em> 形参。</p>
<p>Happy Eyeballs 算法:成功使用双栈主机。 当服务器的 IPv4 路径和协议工作正常,但服务器的 IPv6 路径和协议工作不正常时,双栈客户端应用程序相比单独 IPv4 客户端会感受到明显的连接延迟。 这是不可接受的因为它会导致双栈客户端糟糕的用户体验。 此文档指明了减少这种用户可见延迟的算法要求并提供了具体的算法。</p>
<p>详情参见: <a class="reference external" href="https://tools.ietf.org/html/rfc6555">https://tools.ietf.org/html/rfc6555</a></p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>套接字选项 <code class="xref py py-data docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code> 默认已为所有 TCP 连接进行了设置。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span><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> 类中添加 SSL/TLS 支持。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><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> 函数是一个高层级的替代 API。 它返回一对 (<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>),可在 async/await 代码中直接使用。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.create_datagram_endpoint">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_datagram_endpoint</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">local_addr=None</em>, <em class="sig-param">remote_addr=None</em>, <em class="sig-param">*</em>, <em class="sig-param">family=0</em>, <em class="sig-param">proto=0</em>, <em class="sig-param">flags=0</em>, <em class="sig-param">reuse_address=None</em>, <em class="sig-param">reuse_port=None</em>, <em class="sig-param">allow_broadcast=None</em>, <em class="sig-param">sock=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_datagram_endpoint" title="永久链接至目标"></a></dt>
<dd><div class="admonition note">
<p class="admonition-title">注解</p>
<p>形参 <em>reuse_address</em> 已不再受支持,因为使用 <code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code> 会对 UDP 造成显著的安全问题。 显式地传入 <code class="docutils literal notranslate"><span class="pre">reuse_address=True</span></code> 将会引发异常。</p>
<p>当具有不同 UID 的多个进程将套接字赋给具有 <code class="docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code> 的相同 UDP 套接字地址时,传入的数据包可能会在套接字间随机分配。</p>
<p>对于受支持的平台,<em>reuse_port</em> 可以被用作类似功能的替代。 通过 <em>reuse_port</em> 将改用 <code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEPORT</span></code>,它能够防止具有不同 UID 的进程将套接字赋给相同的套接字地址。</p>
</div>
<p>创建一个数据报连接。</p>
<p>套接字族可以是 <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a>, <a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a><a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>,具体取决于 <em>host</em> (或 <em>family</em> 参数,如果有提供的话)。</p>
<p>socket类型将是 <a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a></p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">协议</span></a> 实现的可调用对象。</p>
<p>成功时返回一个 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 元组。</p>
<p>其他参数:</p>
<ul class="simple">
<li><p><em>local_addr</em>,如果指定的话,就是一个 <code class="docutils literal notranslate"><span class="pre">(local_host,</span> <span class="pre">local_port)</span></code> 元组,用于在本地绑定套接字。 <em>local_host</em><em>local_port</em> 是使用 <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>
<li><p><em>remote_addr</em>,如果指定的话,就是一个 <code class="docutils literal notranslate"><span class="pre">(remote_host,</span> <span class="pre">remote_port)</span></code> 元组,用于同一个远程地址连接。<em>remote_host</em><em>remote_port</em> 是使用 <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>
<li><p><em>family</em>, <em>proto</em>, <em>flags</em> 是可选的地址族,协议和标志,其会被传递给 <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> 来完成 <em>host</em> 的解析。如果要指定的话,这些都应该是来自于 <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> 模块的对应常量。</p></li>
<li><p><em>reuse_port</em> 告知内核,只要在创建时都设置了这个旗标,就允许此端点绑定到其他现有端点所绑定的相同端口上。 这个选项在 Windows 和某些 Unix 上不受支持。 如果 <code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEPORT</span></code> 常量未定义则此功能就是不受支持的。</p></li>
<li><p><em>allow_broadcast</em> 告知内核允许此端点向广播地址发送消息。</p></li>
<li><p><em>sock</em> 可选择通过指定此值用于使用一个预先存在的,已经处于连接状态的 <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> 对象,并将其提供给此传输对象使用。如果指定了这个值, <em>local_addr</em><em>remote_addr</em> 就应该被忽略 (必须为 <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></li>
</ul>
<p>参见 <a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-client-protocol"><span class="std std-ref">UDP echo 客户端协议</span></a><a class="reference internal" href="asyncio-protocol.html#asyncio-udp-echo-server-protocol"><span class="std std-ref">UDP echo 服务端协议</span></a> 的例子。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4.4 版更改: </span>添加了 <em>family</em>, <em>proto</em>, <em>flags</em>, <em>reuse_address</em>, <em>reuse_port</em>, <em>allow_broadcast</em><em>sock</em> 等参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8.1 版更改: </span>出于安全考虑,<em>reuse_address</em> 形参已不再受支持。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版更改: </span>添加WIndows的支持。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.create_unix_connection">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_unix_connection</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">path=None</em>, <em class="sig-param">*</em>, <em class="sig-param">ssl=None</em>, <em class="sig-param">sock=None</em>, <em class="sig-param">server_hostname=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_connection" title="永久链接至目标"></a></dt>
<dd><p>创建Unix 连接</p>
<p>套接字族将为 <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>;套接字类型将为 <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a></p>
<p>成功时返回一个 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 元组。</p>
<p><em>path</em> 是所要求的 Unix 域套接字的名字,除非指定了 <em>sock</em> 形参。 抽象的 Unix 套接字, <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><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> 路径都是受支持的。</p>
<p>请查看 <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> 方法的文档了解有关此方法的参数的信息。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><em>path</em> 形参现在可以是 <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a> 对象。</p>
</div>
</dd></dl>
</section>
<section id="creating-network-servers">
<h3><a class="toc-backref" href="#id7">创建网络服务</a><a class="headerlink" href="#creating-network-servers" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.create_server">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_server</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">host=None</em>, <em class="sig-param">port=None</em>, <em class="sig-param">*</em>, <em class="sig-param">family=socket.AF_UNSPEC</em>, <em class="sig-param">flags=socket.AI_PASSIVE</em>, <em class="sig-param">sock=None</em>, <em class="sig-param">backlog=100</em>, <em class="sig-param">ssl=None</em>, <em class="sig-param">reuse_address=None</em>, <em class="sig-param">reuse_port=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em>, <em class="sig-param">start_serving=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_server" title="永久链接至目标"></a></dt>
<dd><p>创建TCP服务 (socket 类型 <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> ) 监听 <em>host</em> 地址的 <em>port</em> 端口。</p>
<p>返回一个 <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> 对象。</p>
<p>参数:</p>
<ul class="simple">
<li><p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">协议</span></a> 实现的可调用对象。</p></li>
<li><p><em>host</em> 形参可被设为几种类型,它确定了服务器所应监听的位置:</p>
<ul>
<li><p>如果 <em>host</em> 是一个字符串,则 TCP 服务器会被绑定到 <em>host</em> 所指明的单一网络接口。</p></li>
<li><p>如果 <em>host</em> 是一个字符串序列,则 TCP 服务器会被绑定到序列所指明的所有网络接口。</p></li>
<li><p>如果 <em>host</em> 是一个空字符串或 <code class="docutils literal notranslate"><span class="pre">None</span></code>,则会应用所有接口并将返回包含多个套接字的列表(通常是一个 IPv4 的加一个 IPv6 的)。</p></li>
</ul>
</li>
<li><p><em>family</em> 可被设为 <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">socket.AF_INET</span></code></a><a class="reference internal" href="socket.html#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> 以强制此套接字使用 IPv4 或 IPv6。 如果未设定,则 <em>family</em> 将通过主机名称来确定 (默认为 <code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNSPEC</span></code>)。</p></li>
<li><p><em>flags</em> 是用于 <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>
<li><p>可以选择指定 <em>sock</em> 以便使用预先存在的套接字对象。 如果指定了此参数,则不可再指定 <em>host</em><em>port</em></p></li>
<li><p><em>backlog</em> 是传递给 <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> 的最大排队连接的数量默认为100</p></li>
<li><p><em>ssl</em> 可被设置为一个 <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> 实例以在所接受的连接上启用 TLS。</p></li>
<li><p><em>reuse_address</em> 告知内核要重用一个处于 <code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> 状态的本地套接字,而不是等待其自然超时失效。 如果未指定此参数则在 Unix 上将自动设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code></p></li>
<li><p><em>reuse_port</em> 告知内核,只要在创建的时候都设置了这个标志,就允许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在 Windows 上是不支持的。</p></li>
<li><p><em>ssl_handshake_timeout</em> 是(用于 TLS 服务器的)在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 (默认值) <code class="docutils literal notranslate"><span class="pre">None</span></code> 则为 <code class="docutils literal notranslate"><span class="pre">60.0</span></code> 秒。</p></li>
<li><p><em>start_serving</em> 设置成 <code class="docutils literal notranslate"><span class="pre">True</span></code> (默认值) 会导致创建server并立即开始接受连接。设置成 <code class="docutils literal notranslate"><span class="pre">False</span></code> ,用户需要等待 <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> 或者 <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> 以使server开始接受连接。</p></li>
</ul>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span>增加了 <em>ssl_handshake_timeout</em><em>start_serving</em> 形参。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>套接字选项 <code class="xref py py-data docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code> 默认已为所有 TCP 连接进行了设置。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span><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> 类中添加 SSL/TLS 支持。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5.1 版更改: </span><em>host</em> 形参可以是一个字符串的序列。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><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> 函数是一个高层级的替代 API它返回一对 <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>,可在 async/await 代码中使用。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.create_unix_server">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">create_unix_server</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">path=None</em>, <em class="sig-param">*</em>, <em class="sig-param">sock=None</em>, <em class="sig-param">backlog=100</em>, <em class="sig-param">ssl=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em>, <em class="sig-param">start_serving=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.create_unix_server" title="永久链接至目标"></a></dt>
<dd><p><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> 类似但是专用于 <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> 套接字族。</p>
<p><em>path</em> 是必要的 Unix 域套接字名称,除非提供了 <em>sock</em> 参数。 抽象的 Unix 套接字, <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><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> 路径都是受支持的。</p>
<p>请查看 <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>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span>The <em>ssl_handshake_timeout</em> and <em>start_serving</em> parameters.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><em>path</em> 形参现在可以是 <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> 对象。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.connect_accepted_socket">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">connect_accepted_socket</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">sock</em>, <em class="sig-param">*</em>, <em class="sig-param">ssl=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_accepted_socket" title="永久链接至目标"></a></dt>
<dd><p>将已被接受的连接包装成一个传输/协议对。</p>
<p>此方法可被服务器用来接受 asyncio 以外的连接,但是使用 asyncio 来处理它们。</p>
<p>参数:</p>
<ul class="simple">
<li><p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">协议</span></a> 实现的可调用对象。</p></li>
<li><p><em>sock</em> 是一个预先存在的套接字对象,它是由 <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></li>
<li><p><em>ssl</em> 可被设置为一个 <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> 以在接受的连接上启用 SSL。</p></li>
<li><p><em>ssl_handshake_timeout</em> 是(为一个SSL连接)在中止连接前等待SSL握手完成的时间【单位秒】。如果为 <code class="docutils literal notranslate"><span class="pre">None</span></code> (缺省) 则是 <code class="docutils literal notranslate"><span class="pre">60.0</span></code> 秒。</p></li>
</ul>
<p>返回一个 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code> 对。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能: </span><em>ssl_handshake_timeout</em> 形参。</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.5.3 新版功能.</span></p>
</div>
</dd></dl>
</section>
<section id="transferring-files">
<h3><a class="toc-backref" href="#id8">传输文件</a><a class="headerlink" href="#transferring-files" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.sendfile">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sendfile</code><span class="sig-paren">(</span><em class="sig-param">transport</em>, <em class="sig-param">file</em>, <em class="sig-param">offset=0</em>, <em class="sig-param">count=None</em>, <em class="sig-param">*</em>, <em class="sig-param">fallback=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sendfile" title="永久链接至目标"></a></dt>
<dd><p><em>file</em> 通过 <em>transport</em> 发送。 返回所发送的字节总数。</p>
<p>如果可用的话,该方法将使用高性能的 <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></p>
<p><em>file</em> 必须是个二进制模式打开的常规文件对象。</p>
<p><em>offset</em> 指明从何处开始读取文件。 如果指定了 <em>count</em>,它是要传输的字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新,即使此方法引发了错误,并可以使用 <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> 来获取实际发送的字节总数。</p>
<p><em>fallback</em> 设为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 会使得 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件(例如 Windows 或 Unix 上的 SSL 套接字)。</p>
<p>如果系统不支持 <em>sendfile</em> 系统调用且 <em>fallback</em><code class="docutils literal notranslate"><span class="pre">False</span></code> 则会引发 <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></p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</section>
<section id="tls-upgrade">
<h3><a class="toc-backref" href="#id9">TLS 升级</a><a class="headerlink" href="#tls-upgrade" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.start_tls">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">start_tls</code><span class="sig-paren">(</span><em class="sig-param">transport</em>, <em class="sig-param">protocol</em>, <em class="sig-param">sslcontext</em>, <em class="sig-param">*</em>, <em class="sig-param">server_side=False</em>, <em class="sig-param">server_hostname=None</em>, <em class="sig-param">ssl_handshake_timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.start_tls" title="永久链接至目标"></a></dt>
<dd><p>将现有基于传输的连接升级到 TLS。</p>
<p>返回一个新的传输实例,其中 <em>protocol</em> 必须在 <em>await</em> 之后立即开始使用。 传给 <em>start_tls</em> 方法的 <em>transport</em> 实例应永远不会被再次使用。</p>
<p>参数:</p>
<ul class="simple">
<li><p><em>transport</em><em>protocol</em> 实例的方法与 <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><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> 所返回的类似。</p></li>
<li><p><em>sslcontext</em> :一个已经配置好的 <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>
<li><p>当服务端连接已升级时 (如 <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> 所创建的对象) <em>server_side</em> 会传入 <code class="docutils literal notranslate"><span class="pre">True</span></code></p></li>
<li><p><em>server_hostname</em> :设置或者覆盖目标服务器证书中相对应的主机名。</p></li>
<li><p><em>ssl_handshake_timeout</em> 是(用于 TLS 连接的)在放弃连接之前要等待 TLS 握手完成的秒数。 如果参数为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 则使用 (默认的) <code class="docutils literal notranslate"><span class="pre">60.0</span></code></p></li>
</ul>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</section>
<section id="watching-file-descriptors">
<h3><a class="toc-backref" href="#id10">监控文件描述符</a><a class="headerlink" href="#watching-file-descriptors" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.add_reader">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">add_reader</code><span class="sig-paren">(</span><em class="sig-param">fd</em>, <em class="sig-param">callback</em>, <em class="sig-param">*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_reader" title="永久链接至目标"></a></dt>
<dd><p>开始监视 <em>fd</em> 文件描述符以获取读取的可用性,一旦 <em>fd</em> 可用于读取,使用指定的参数调用 <em>callback</em></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.remove_reader">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">remove_reader</code><span class="sig-paren">(</span><em class="sig-param">fd</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_reader" title="永久链接至目标"></a></dt>
<dd><p>停止对文件描述符 <em>fd</em> 读取可用性的监视。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.add_writer">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">add_writer</code><span class="sig-paren">(</span><em class="sig-param">fd</em>, <em class="sig-param">callback</em>, <em class="sig-param">*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_writer" title="永久链接至目标"></a></dt>
<dd><p>开始监视 <em>fd</em> 文件描述符的写入可用性,一旦 <em>fd</em> 可用于写入,使用指定的参数调用 <em>callback</em></p>
<p>使用 <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">传递关键字参数</span></a><em>callback</em>.</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.remove_writer">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">remove_writer</code><span class="sig-paren">(</span><em class="sig-param">fd</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_writer" title="永久链接至目标"></a></dt>
<dd><p>停止对文件描述符 <em>fd</em> 的写入可用性监视。</p>
</dd></dl>
<p>另请查看 <a class="reference internal" href="asyncio-platforms.html#asyncio-platform-support"><span class="std std-ref">平台支持</span></a> 一节了解以上方法的某些限制。</p>
</section>
<section id="working-with-socket-objects-directly">
<h3><a class="toc-backref" href="#id11">直接使用 socket 对象</a><a class="headerlink" href="#working-with-socket-objects-directly" title="永久链接至标题"></a></h3>
<p>通常,使用基于传输的 API 的协议实现,例如 <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><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> 比直接使用套接字的实现更快。 但是,在某些应用场景下性能并不非常重要,直接使用 <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> 对象会更方便。</p>
<dl class="method">
<dt id="asyncio.loop.sock_recv">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_recv</code><span class="sig-paren">(</span><em class="sig-param">sock</em>, <em class="sig-param">nbytes</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_recv" title="永久链接至目标"></a></dt>
<dd><p><em>sock</em> 接收至多 <em>nbytes</em><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>
<p>返回接收到的数据【bytes对象类型】。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>虽然这个方法总是被记录为协程方法,但它在 Python 3.7 之前的发行版中会返回一个 <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>。 从 Python 3.7 开始它则是一个 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.sock_recv_into">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_recv_into</code><span class="sig-paren">(</span><em class="sig-param">sock</em>, <em class="sig-param">buf</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_recv_into" title="永久链接至目标"></a></dt>
<dd><p><em>sock</em> 接收数据放入 <em>buf</em> 缓冲区。 模仿了阻塞型的 <a class="reference internal" href="socket.html#socket.socket.recv_into" title="socket.socket.recv_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.recv_into()</span></code></a> 方法。</p>
<p>返回写入缓冲区的字节数。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.sock_sendall">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_sendall</code><span class="sig-paren">(</span><em class="sig-param">sock</em>, <em class="sig-param">data</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_sendall" title="永久链接至目标"></a></dt>
<dd><p><em>data</em> 发送到 <em>sock</em> 套接字。 <a class="reference internal" href="socket.html#socket.socket.sendall" title="socket.socket.sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.sendall()</span></code></a> 的异步版本。</p>
<p>此方法会持续发送数据到套接字直至 <em>data</em> 中的所有数据发送完毕或是有错误发生。 当成功时会返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>。 当发生错误时,会引发一个异常。 此外,没有办法能确定有多少数据或是否有数据被连接的接收方成功处理。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>虽然这个方法一直被标记为协程方法。但是Python 3.7 之前,该方法返回 <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> 从Python 3.7 开始,这个方法是 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.sock_connect">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_connect</code><span class="sig-paren">(</span><em class="sig-param">sock</em>, <em class="sig-param">address</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_connect" title="永久链接至目标"></a></dt>
<dd><p><em>sock</em> 连接到位于 <em>address</em> 的远程套接字。</p>
<p><a class="reference internal" href="socket.html#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a> 的异步版本。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5.2 版更改: </span><code class="docutils literal notranslate"><span class="pre">address</span></code> 不再需要被解析。 <code class="docutils literal notranslate"><span class="pre">sock_connect</span></code> 将尝试检查 <em>address</em> 是否已通过调用 <a class="reference internal" href="socket.html#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.inet_pton()</span></code></a> 被解析。 如果没有,则将使用 <a class="reference internal" href="#asyncio.loop.getaddrinfo" title="asyncio.loop.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.getaddrinfo()</span></code></a> 来解析 <em>address</em></p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><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><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">asyncio.open_connection()</span></code></a></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.sock_accept">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_accept</code><span class="sig-paren">(</span><em class="sig-param">sock</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_accept" title="永久链接至目标"></a></dt>
<dd><p>接受一个连接。 模仿了阻塞型的 <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>
<p><em>scoket</em> 必须绑定到一个地址上并且监听连接。返回值是一个 <code class="docutils literal notranslate"><span class="pre">(conn,</span> <span class="pre">address)</span></code> 对,其中 <em>conn</em> 是一个 <em>新*的套接字对象,用于在此连接上收发数据,*address</em> 是连接的另一端的套接字所绑定的地址。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>虽然这个方法一直被标记为协程方法。但是Python 3.7 之前,该方法返回 <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> 从Python 3.7 开始,这个方法是 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code> 方法。</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><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><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></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.sock_sendfile">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">sock_sendfile</code><span class="sig-paren">(</span><em class="sig-param">sock</em>, <em class="sig-param">file</em>, <em class="sig-param">offset=0</em>, <em class="sig-param">count=None</em>, <em class="sig-param">*</em>, <em class="sig-param">fallback=True</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.sock_sendfile" title="永久链接至目标"></a></dt>
<dd><p>在可能的情况下使用高性能的 <a class="reference internal" href="os.html#os.sendfile" title="os.sendfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.sendfile</span></code></a> 发送文件。 返回所发送的字节总数。</p>
<p><a class="reference internal" href="socket.html#socket.socket.sendfile" title="socket.socket.sendfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.sendfile()</span></code></a> 的异步版本。</p>
<p><em>sock</em> 必须为非阻塞型的 <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">socket.SOCK_STREAM</span></code></a> <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></p>
<p><em>file</em> 必须是个用二进制方式打开的常规文件对象。</p>
<p><em>offset</em> 指明从何处开始读取文件。 如果指定了 <em>count</em>,它是要传输的字节总数而不再一直发送文件直至抵达 EOF。 文件位置总是会被更新,即使此方法引发了错误,并可以使用 <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> 来获取实际发送的字节总数。</p>
<p><em>fallback</em> 被设为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时,会使用 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件(例如 Windows 或 Unix 上的 SSL 套接字)。</p>
<p>如果系统不支持 <em>sendfile</em> 并且 <em>fallback</em><code class="docutils literal notranslate"><span class="pre">False</span></code> ,引发 <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> 异常。</p>
<p><em>sock</em> 必须是个非阻塞socket。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</section>
<section id="dns">
<h3><a class="toc-backref" href="#id12">DNS</a><a class="headerlink" href="#dns" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.getaddrinfo">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">getaddrinfo</code><span class="sig-paren">(</span><em class="sig-param">host</em>, <em class="sig-param">port</em>, <em class="sig-param">*</em>, <em class="sig-param">family=0</em>, <em class="sig-param">type=0</em>, <em class="sig-param">proto=0</em>, <em class="sig-param">flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.getaddrinfo" title="永久链接至目标"></a></dt>
<dd><p>异步版的 <a class="reference internal" href="socket.html#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getaddrinfo()</span></code></a></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.getnameinfo">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">getnameinfo</code><span class="sig-paren">(</span><em class="sig-param">sockaddr</em>, <em class="sig-param">flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.getnameinfo" title="永久链接至目标"></a></dt>
<dd><p>异步版的 <a class="reference internal" href="socket.html#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.getnameinfo()</span></code></a></p>
</dd></dl>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span><em>getaddrinfo</em><em>getnameinfo</em> 方法一直被标记返回一个协程但是Python 3.7之前,实际返回的是 <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> 对象。从Python 3.7 开始,这两个方法是协程。</p>
</div>
</section>
<section id="working-with-pipes">
<h3><a class="toc-backref" href="#id13">使用管道</a><a class="headerlink" href="#working-with-pipes" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.connect_read_pipe">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">connect_read_pipe</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">pipe</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_read_pipe" title="永久链接至目标"></a></dt>
<dd><p>在事件循环中注册 <em>pipe</em> 的读取端。</p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio 协议</span></a> 实现的可调用对象。</p>
<p><em>pipe</em> 是个 <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">类似文件型对象</span></a>.</p>
<p>返回一对 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>,其中 <em>transport</em> 支持 <a class="reference internal" href="asyncio-protocol.html#asyncio.ReadTransport" title="asyncio.ReadTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">ReadTransport</span></code></a> 接口而 <em>protocol</em> 是由 <em>protocol_factory</em> 所实例化的对象。</p>
<p>使用 <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> 事件循环, <em>pipe</em> 被设置为非阻塞模式。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.connect_write_pipe">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">connect_write_pipe</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">pipe</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.connect_write_pipe" title="永久链接至目标"></a></dt>
<dd><p>在事件循环中注册 <em>pipe</em> 的写入端。</p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">asyncio 协议</span></a> 实现的可调用对象。</p>
<p><em>pipe</em> 是个 <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">类似文件型对象</span></a>.</p>
<p>返回一对 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>,其中 <em>transport</em> 支持 <a class="reference internal" href="asyncio-protocol.html#asyncio.WriteTransport" title="asyncio.WriteTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">WriteTransport</span></code></a> 接口而 <em>protocol</em> 是由 <em>protocol_factory</em> 所实例化的对象。</p>
<p>使用 <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> 事件循环, <em>pipe</em> 被设置为非阻塞模式。</p>
</dd></dl>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>在 Windows 中 <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> 不支持上述方法。 对于 Windows 请改用 <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>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_exec()</span></code></a><a class="reference internal" href="#asyncio.loop.subprocess_shell" title="asyncio.loop.subprocess_shell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.subprocess_shell()</span></code></a> 方法。</p>
</div>
</section>
<section id="unix-signals">
<h3><a class="toc-backref" href="#id14">Unix 信号</a><a class="headerlink" href="#unix-signals" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.add_signal_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">add_signal_handler</code><span class="sig-paren">(</span><em class="sig-param">signum</em>, <em class="sig-param">callback</em>, <em class="sig-param">*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.add_signal_handler" title="永久链接至目标"></a></dt>
<dd><p>设置 <em>callback</em> 作为 <em>signum</em> 信号的处理程序。</p>
<p>此回调将与该事件循环中其他加入队列的回调和可运行协程一起由 <em>loop</em> 发起调用。 不同与使用 <a class="reference internal" href="signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a> 注册的信号处理程序,使用此函数注册的回调可以与事件循环进行交互。</p>
<p>如果信号数字非法或者不可捕获,就抛出一个 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></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>
<p>使用 <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">传递关键字参数</span></a><em>callback</em>.</p>
<p><a class="reference internal" href="signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a> 一样,这个函数只能在主线程中调用。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.remove_signal_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">remove_signal_handler</code><span class="sig-paren">(</span><em class="sig-param">sig</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.remove_signal_handler" title="永久链接至目标"></a></dt>
<dd><p>移除 <em>sig</em> 信号的处理程序。</p>
<p>如果信号处理程序被移除则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code>,否则如果给定信号未设置处理程序则返回 <code class="docutils literal notranslate"><span class="pre">False</span></code></p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix。</p>
</dd></dl>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> 模块。</p>
</div>
</section>
<section id="executing-code-in-thread-or-process-pools">
<h3><a class="toc-backref" href="#id15">在线程或者进程池中执行代码。</a><a class="headerlink" href="#executing-code-in-thread-or-process-pools" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.run_in_executor">
<em class="property">awaitable </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">run_in_executor</code><span class="sig-paren">(</span><em class="sig-param">executor</em>, <em class="sig-param">func</em>, <em class="sig-param">*args</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.run_in_executor" title="永久链接至目标"></a></dt>
<dd><p>安排在指定的执行器中调用 <em>func</em></p>
<p>The <em>executor</em> argument should be an <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Executor" title="concurrent.futures.Executor"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Executor</span></code></a>
instance. The default executor is used if <em>executor</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">concurrent.futures</span>
<span class="k">def</span> <span class="nf">blocking_io</span><span class="p">():</span>
<span class="c1"># File operations (such as logging) can block the</span>
<span class="c1"># event loop: run them in a thread pool.</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/dev/urandom&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="k">return</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">cpu_bound</span><span class="p">():</span>
<span class="c1"># CPU-bound operations will block the event loop:</span>
<span class="c1"># in general it is preferable to run them in a</span>
<span class="c1"># process pool.</span>
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">i</span> <span class="o">*</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span> <span class="o">**</span> <span class="mi">7</span><span class="p">))</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_loop</span><span class="p">()</span>
<span class="c1">## Options:</span>
<span class="c1"># 1. Run in the default loop&#39;s executor:</span>
<span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
<span class="kc">None</span><span class="p">,</span> <span class="n">blocking_io</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;default thread pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
<span class="c1"># 2. Run in a custom thread pool:</span>
<span class="k">with</span> <span class="n">concurrent</span><span class="o">.</span><span class="n">futures</span><span class="o">.</span><span class="n">ThreadPoolExecutor</span><span class="p">()</span> <span class="k">as</span> <span class="n">pool</span><span class="p">:</span>
<span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
<span class="n">pool</span><span class="p">,</span> <span class="n">blocking_io</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;custom thread pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
<span class="c1"># 3. Run in a custom process pool:</span>
<span class="k">with</span> <span class="n">concurrent</span><span class="o">.</span><span class="n">futures</span><span class="o">.</span><span class="n">ProcessPoolExecutor</span><span class="p">()</span> <span class="k">as</span> <span class="n">pool</span><span class="p">:</span>
<span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">run_in_executor</span><span class="p">(</span>
<span class="n">pool</span><span class="p">,</span> <span class="n">cpu_bound</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;custom process pool&#39;</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
<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>
</pre></div>
</div>
<p>这个方法返回一个 <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> 对象。</p>
<p>使用 <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">传递关键字参数</span></a><em>func</em></p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5.3 版更改: </span><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> 不会再配置它所创建的线程池执行器的 <code class="docutils literal notranslate"><span class="pre">max_workers</span></code>,而是将其留给线程池执行器 (<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>) 来设置默认值。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.set_default_executor">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">set_default_executor</code><span class="sig-paren">(</span><em class="sig-param">executor</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_default_executor" title="永久链接至目标"></a></dt>
<dd><p><em>executor</em> 设为 <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">run_in_executor()</span></code></a> 所使用的默认执行器。 <em>executor</em> 应当是 <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> 的实例。</p>
<div class="deprecated">
<p><span class="versionmodified deprecated">3.8 版后已移除: </span>使用不是Using an executor that is not an instance of <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> 实例的执行器的做法已被弃用并将在 Python 3.9 中引起错误。</p>
</div>
<p><em>executor</em> 必须是个 <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">concurrent.futures.ThreadPoolExecutor</span></code></a> 的实例。</p>
</dd></dl>
</section>
<section id="error-handling-api">
<h3><a class="toc-backref" href="#id16">错误处理API</a><a class="headerlink" href="#error-handling-api" title="永久链接至标题"></a></h3>
<p>允许自定义事件循环中如何去处理异常。</p>
<dl class="method">
<dt id="asyncio.loop.set_exception_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">set_exception_handler</code><span class="sig-paren">(</span><em class="sig-param">handler</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_exception_handler" title="永久链接至目标"></a></dt>
<dd><p><em>handler</em> 设置为新的事件循环异常处理器。</p>
<p>如果 <em>handler</em><code class="docutils literal notranslate"><span class="pre">None</span></code>,将设置默认的异常处理程序。 在其他情况下,<em>handler</em> 必须是一个可调用对象且签名匹配 <code class="docutils literal notranslate"><span class="pre">(loop,</span> <span class="pre">context)</span></code>,其中 <code class="docutils literal notranslate"><span class="pre">loop</span></code> 是对活动事件循环的引用,而 <code class="docutils literal notranslate"><span class="pre">context</span></code> 是一个包含异常详情的 <code class="docutils literal notranslate"><span class="pre">dict</span></code> (请查看 <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_exception_handler()</span></code></a> 文档来获取关于上下文的更多信息)。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.get_exception_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">get_exception_handler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_exception_handler" title="永久链接至目标"></a></dt>
<dd><p>返回当前的异常处理器,如果没有设置异常处理器,则返回 <code class="docutils literal notranslate"><span class="pre">None</span></code></p>
<div class="versionadded">
<p><span class="versionmodified added">3.5.2 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.default_exception_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">default_exception_handler</code><span class="sig-paren">(</span><em class="sig-param">context</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.default_exception_handler" title="永久链接至目标"></a></dt>
<dd><p>默认的异常处理器。</p>
<p>此方法会在发生异常且未设置异常处理程序时被调用。 此方法也可以由想要具有不同于默认处理程序的行为的自定义异常处理程序来调用。</p>
<p><em>context</em> 参数和 <a class="reference internal" href="#asyncio.loop.call_exception_handler" title="asyncio.loop.call_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_exception_handler()</span></code></a> 中的同名参数完全相同。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.call_exception_handler">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">call_exception_handler</code><span class="sig-paren">(</span><em class="sig-param">context</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.call_exception_handler" title="永久链接至目标"></a></dt>
<dd><p>调用当前事件循环的异常处理器。</p>
<p><em>context</em> 是个包含下列键的 <code class="docutils literal notranslate"><span class="pre">dict</span></code> 对象(未来版本的Python可能会引入新键)</p>
<ul class="simple">
<li><p>'message': 错误消息;</p></li>
<li><p>'exception' (可选): 异常对象;</p></li>
<li><p>'future' (可选): <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> 实例;</p></li>
<li><p>'handle' (可选): <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> 实例;</p></li>
<li><p>'protocol' (可选): <a class="reference internal" href="asyncio-protocol.html#asyncio-protocol"><span class="std std-ref">Protocol</span></a> 实例;</p></li>
<li><p>'transport' (可选): <a class="reference internal" href="asyncio-protocol.html#asyncio-transport"><span class="std std-ref">Transport</span></a> 实例;</p></li>
<li><p>'socket' (可选): <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> 实例。</p></li>
</ul>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>此方法不应在子类化的事件循环中被重载。 对于自定义的异常处理,请使用 <a class="reference internal" href="#asyncio.loop.set_exception_handler" title="asyncio.loop.set_exception_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception_handler()</span></code></a> 方法。</p>
</div>
</dd></dl>
</section>
<section id="enabling-debug-mode">
<h3><a class="toc-backref" href="#id17">开启调试模式</a><a class="headerlink" href="#enabling-debug-mode" title="永久链接至标题"></a></h3>
<dl class="method">
<dt id="asyncio.loop.get_debug">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">get_debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.get_debug" title="永久链接至目标"></a></dt>
<dd><p>获取事件循环调试模式设置(<a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>)。</p>
<p>如果环境变量 <span class="target" id="index-17"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONASYNCIODEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONASYNCIODEBUG</span></code></a> 是一个非空字符串,就返回 <code class="docutils literal notranslate"><span class="pre">True</span></code> ,否则就返回 <code class="docutils literal notranslate"><span class="pre">False</span></code></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.set_debug">
<code class="sig-prename descclassname">loop.</code><code class="sig-name descname">set_debug</code><span class="sig-paren">(</span><em class="sig-param">enabled: bool</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.set_debug" title="永久链接至目标"></a></dt>
<dd><p>设置事件循环的调试模式。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>The new <code class="docutils literal notranslate"><span class="pre">-X</span> <span class="pre">dev</span></code> command line option can now also be used
to enable the debug mode.</p>
</div>
</dd></dl>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference internal" href="asyncio-dev.html#asyncio-debug-mode"><span class="std std-ref">debug mode of asyncio</span></a>.</p>
</div>
</section>
<section id="running-subprocesses">
<h3><a class="toc-backref" href="#id18">运行子进程</a><a class="headerlink" href="#running-subprocesses" title="永久链接至标题"></a></h3>
<p>本小节所描述的方法都是低层级的。 在常规 async/await 代码中请考虑改用高层级的 <a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_shell" title="asyncio.create_subprocess_shell"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_subprocess_shell()</span></code></a><a class="reference internal" href="asyncio-subprocess.html#asyncio.create_subprocess_exec" title="asyncio.create_subprocess_exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.create_subprocess_exec()</span></code></a> 便捷函数。</p>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p><strong>Windows</strong> 中默认的 asyncio 事件循环不支持子进程。 详情参见 <a class="reference internal" href="asyncio-platforms.html#asyncio-windows-subprocess"><span class="std std-ref">Windows 上的子进程支持</span></a></p>
</div>
<dl class="method">
<dt id="asyncio.loop.subprocess_exec">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">subprocess_exec</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">*args</em>, <em class="sig-param">stdin=subprocess.PIPE</em>, <em class="sig-param">stdout=subprocess.PIPE</em>, <em class="sig-param">stderr=subprocess.PIPE</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.subprocess_exec" title="永久链接至目标"></a></dt>
<dd><p><em>args</em> 指定的一个或者多个字符串型参数创建一个子进程。</p>
<p><em>args</em> 必须是个由下列形式的字符串组成的列表:</p>
<ul class="simple">
<li><p><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>;</p></li>
<li><p>或者由 <a class="reference internal" href="os.html#filesystem-encoding"><span class="std std-ref">文件系统编码格式</span></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></p></li>
</ul>
<p>第一个字符串指定可执行程序,其余的字符串指定其参数。 所有字符串参数共同组成了程序的 <code class="docutils literal notranslate"><span class="pre">argv</span></code></p>
<p>此方法类似于调用标准库 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> 类,设置 <code class="docutils literal notranslate"><span class="pre">shell=False</span></code> 并将字符串列表作为第一个参数传入;但是,<a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> 只接受一个单独的字符串列表参数,而 <em>subprocess_exec</em> 接受多个字符串参数。</p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.SubprocessProtocol</span></code></a> 类的子类的可调用对象。</p>
<p>其他参数:</p>
<ul>
<li><p><em>stdin</em> 可以是以下对象之一:</p>
<ul class="simple">
<li><p>一个文件型对象,表示要使用 <a class="reference internal" href="#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_write_pipe()</span></code></a> 连接到子进程的标准输入流的管道</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> 常量(默认),将创建并连接一个新的管道。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">None</span></code> 值,这将使得子进程继承来自此进程的文件描述符</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.DEVNULL" title="subprocess.DEVNULL"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.DEVNULL</span></code></a> 常量,这表示将使用特殊的 <a class="reference internal" href="os.html#os.devnull" title="os.devnull"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.devnull</span></code></a> 文件</p></li>
</ul>
</li>
<li><p><em>stdout</em> 可以是以下对象之一:</p>
<ul class="simple">
<li><p>一个文件型对象,表示要使用 <a class="reference internal" href="#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_write_pipe()</span></code></a> 连接到子进程的标准输出流的管道</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> 常量(默认),将创建并连接一个新的管道。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">None</span></code> 值,这将使得子进程继承来自此进程的文件描述符</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.DEVNULL" title="subprocess.DEVNULL"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.DEVNULL</span></code></a> 常量,这表示将使用特殊的 <a class="reference internal" href="os.html#os.devnull" title="os.devnull"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.devnull</span></code></a> 文件</p></li>
</ul>
</li>
<li><p><em>stderr</em> 可以是以下对象之一:</p>
<ul class="simple">
<li><p>一个文件型对象,表示要使用 <a class="reference internal" href="#asyncio.loop.connect_write_pipe" title="asyncio.loop.connect_write_pipe"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect_write_pipe()</span></code></a> 连接到子进程的标准错误流的管道</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code></a> 常量(默认),将创建并连接一个新的管道。</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">None</span></code> 值,这将使得子进程继承来自此进程的文件描述符</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.DEVNULL" title="subprocess.DEVNULL"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.DEVNULL</span></code></a> 常量,这表示将使用特殊的 <a class="reference internal" href="os.html#os.devnull" title="os.devnull"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.devnull</span></code></a> 文件</p></li>
<li><p><a class="reference internal" href="subprocess.html#subprocess.STDOUT" title="subprocess.STDOUT"><code class="xref py py-const docutils literal notranslate"><span class="pre">subprocess.STDOUT</span></code></a> 常量,将把标准错误流连接到进程的标准输出流</p></li>
</ul>
</li>
<li><p>所有其他关键字参数会被不加解释地传给 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a>,除了 <em>bufsize</em>, <em>universal_newlines</em>, <em>shell</em>, <em>text</em>, <em>encoding</em><em>errors</em>,它们都不应当被指定。</p>
<p><code class="docutils literal notranslate"><span class="pre">asyncio</span></code> 子进程 API 不支持将流解码为文本。 可以使用 <a class="reference internal" href="stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a> 来将从流返回的字节串转换为文本。</p>
</li>
</ul>
<p>其他参数的文档,请参阅 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> 类的构造函数。</p>
<p>返回一对 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>,其中 <em>transport</em> 来自 <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.SubprocessTransport</span></code></a> 基类而 <em>protocol</em> 是由 <em>protocol_factory</em> 所实例化的对象。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.loop.subprocess_shell">
<em class="property">coroutine </em><code class="sig-prename descclassname">loop.</code><code class="sig-name descname">subprocess_shell</code><span class="sig-paren">(</span><em class="sig-param">protocol_factory</em>, <em class="sig-param">cmd</em>, <em class="sig-param">*</em>, <em class="sig-param">stdin=subprocess.PIPE</em>, <em class="sig-param">stdout=subprocess.PIPE</em>, <em class="sig-param">stderr=subprocess.PIPE</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.loop.subprocess_shell" title="永久链接至目标"></a></dt>
<dd><p>基于 <em>cmd</em> 创建一个子进程,该参数可以是一个 <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="os.html#filesystem-encoding"><span class="std std-ref">文件系统编码格式</span></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> ,使用平台的 &quot;shell&quot; 语法。</p>
<p>这类似与用 <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> 调用标准库的 <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a> 类。</p>
<p><em>protocol_factory</em> 必须为一个返回 <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessProtocol" title="asyncio.SubprocessProtocol"><code class="xref py py-class docutils literal notranslate"><span class="pre">SubprocessProtocol</span></code></a> 类的子类的可调用对象。</p>
<p>请参阅 <a class="reference internal" href="#asyncio.loop.subprocess_exec" title="asyncio.loop.subprocess_exec"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subprocess_exec()</span></code></a> 了解有关其余参数的详情。</p>
<p>返回一对 <code class="docutils literal notranslate"><span class="pre">(transport,</span> <span class="pre">protocol)</span></code>,其中 <em>transport</em> 来自 <a class="reference internal" href="asyncio-protocol.html#asyncio.SubprocessTransport" title="asyncio.SubprocessTransport"><code class="xref py py-class docutils literal notranslate"><span class="pre">SubprocessTransport</span></code></a> 基类而 <em>protocol</em> 是由 <em>protocol_factory</em> 所实例化的对象。</p>
</dd></dl>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>应用程序要负责确保正确地转义所有空白字符和特殊字符以防止 <a class="reference external" href="https://en.wikipedia.org/wiki/Shell_injection#Shell_injection">shell 注入</a> 漏洞。 <a class="reference internal" href="shlex.html#shlex.quote" title="shlex.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">shlex.quote()</span></code></a> 函数可以被用来正确地转义字符串中可能被用来构造 shell 命令的空白字符和特殊字符。</p>
</div>
</section>
</section>
<section id="callback-handles">
<h2>回调处理<a class="headerlink" href="#callback-handles" title="永久链接至标题"></a></h2>
<dl class="class">
<dt id="asyncio.Handle">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">Handle</code><a class="headerlink" href="#asyncio.Handle" title="永久链接至目标"></a></dt>
<dd><p><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>, <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">loop.call_soon_threadsafe()</span></code></a> 所返回的回调包装器对象。</p>
<dl class="method">
<dt id="asyncio.Handle.cancel">
<code class="sig-name descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Handle.cancel" title="永久链接至目标"></a></dt>
<dd><p>取消回调。 如果此回调已被取消或已被执行,此方法将没有任何效果。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Handle.cancelled">
<code class="sig-name descname">cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Handle.cancelled" title="永久链接至目标"></a></dt>
<dd><p>如果此回调已被取消则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</dd></dl>
<dl class="class">
<dt id="asyncio.TimerHandle">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">TimerHandle</code><a class="headerlink" href="#asyncio.TimerHandle" title="永久链接至目标"></a></dt>
<dd><p><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><a class="reference internal" href="#asyncio.loop.call_at" title="asyncio.loop.call_at"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.call_at()</span></code></a> 所返回的回调包装器对象。</p>
<p>这个类是 <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> 的子类。</p>
<dl class="method">
<dt id="asyncio.TimerHandle.when">
<code class="sig-name descname">when</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.TimerHandle.when" title="永久链接至目标"></a></dt>
<dd><p>返回加入计划任务的回调时间,以 <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> 值表示的秒数。</p>
<p>时间值是一个绝对时间戳,使用与 <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>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</dd></dl>
</section>
<section id="server-objects">
<h2>Server 对象<a class="headerlink" href="#server-objects" title="永久链接至标题"></a></h2>
<p>Server 对象可使用 <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>, <a class="reference internal" href="#asyncio.loop.create_unix_server" title="asyncio.loop.create_unix_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_unix_server()</span></code></a>, <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><a class="reference internal" href="asyncio-stream.html#asyncio.start_unix_server" title="asyncio.start_unix_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_unix_server()</span></code></a> 等函数来创建。</p>
<p>请不要直接实例化该类。</p>
<dl class="class">
<dt id="asyncio.Server">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">Server</code><a class="headerlink" href="#asyncio.Server" title="永久链接至目标"></a></dt>
<dd><p><em>Server</em> 对象是异步上下文管理器。当用于 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> 语句时,异步上下文管理器可以确保 Server 对象被关闭,并且在 <code class="docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> 语句完成后,不接受新的连接。</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">srv</span> <span class="o">=</span> <span class="k">await</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_server</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="k">async</span> <span class="k">with</span> <span class="n">srv</span><span class="p">:</span>
<span class="c1"># some code</span>
<span class="c1"># At this point, srv is closed and no longer accepts new connections.</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>Python3.7 开始Server 对象是一个异步上下文管理器。</p>
</div>
<dl class="method">
<dt id="asyncio.Server.close">
<code class="sig-name descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.close" title="永久链接至目标"></a></dt>
<dd><p>停止服务:关闭监听的套接字并且设置 <a class="reference internal" href="#asyncio.Server.sockets" title="asyncio.Server.sockets"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sockets</span></code></a> 属性为 <code class="docutils literal notranslate"><span class="pre">None</span></code></p>
<p>用于表示已经连进来的客户端连接会保持打开的状态。</p>
<p>服务器是被异步关闭的,使用 <a class="reference internal" href="#asyncio.Server.wait_closed" title="asyncio.Server.wait_closed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait_closed()</span></code></a> 协程来等待服务器关闭。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Server.get_loop">
<code class="sig-name descname">get_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.get_loop" title="永久链接至目标"></a></dt>
<dd><p>返回与服务器对象相关联的事件循环。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Server.start_serving">
<em class="property">coroutine </em><code class="sig-name descname">start_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.start_serving" title="永久链接至目标"></a></dt>
<dd><p>开始接受连接。</p>
<p>这个方法是幂等的【相同参数重复执行,能获得相同的结果】,所以此方法能在服务已经运行的时候调用。</p>
<p>传给 <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><a class="reference internal" href="asyncio-stream.html#asyncio.start_server" title="asyncio.start_server"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.start_server()</span></code></a><em>start_serving</em> 仅限关键字形参允许创建不接受初始连接的 Server 对象。 在此情况下可以使用 <code class="docutils literal notranslate"><span class="pre">Server.start_serving()</span></code><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> 让 Server 对象开始接受连接。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Server.serve_forever">
<em class="property">coroutine </em><code class="sig-name descname">serve_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.serve_forever" title="永久链接至目标"></a></dt>
<dd><p>开始接受连接,直到协程被取消。 <code class="docutils literal notranslate"><span class="pre">serve_forever</span></code> 任务的取消将导致服务器被关闭。</p>
<p>如果服务器已经在接受连接了,这个方法可以被调用。每个 <em>Server</em> 对象,仅能有一个 <code class="docutils literal notranslate"><span class="pre">serve_forever</span></code> 任务。</p>
<p>示例:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">async</span> <span class="k">def</span> <span class="nf">client_connected</span><span class="p">(</span><span class="n">reader</span><span class="p">,</span> <span class="n">writer</span><span class="p">):</span>
<span class="c1"># Communicate with the client with</span>
<span class="c1"># reader/writer streams. For example:</span>
<span class="k">await</span> <span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">):</span>
<span class="n">srv</span> <span class="o">=</span> <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">start_server</span><span class="p">(</span>
<span class="n">client_connected</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
<span class="k">await</span> <span class="n">srv</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
<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><span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Server.is_serving">
<code class="sig-name descname">is_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.is_serving" title="永久链接至目标"></a></dt>
<dd><p>如果服务器正在接受新连接的状态,返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Server.wait_closed">
<em class="property">coroutine </em><code class="sig-name descname">wait_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Server.wait_closed" title="永久链接至目标"></a></dt>
<dd><p>等待 <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> 方法执行完毕。</p>
</dd></dl>
<dl class="attribute">
<dt id="asyncio.Server.sockets">
<code class="sig-name descname">sockets</code><a class="headerlink" href="#asyncio.Server.sockets" title="永久链接至目标"></a></dt>
<dd><p>服务器监听的 <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> 对象列表。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>在 Python 3.7 之前 <code class="docutils literal notranslate"><span class="pre">Server.sockets</span></code> 会直接返回内部的服务器套接字列表。 在 3.7 版则会返回该列表的副本。</p>
</div>
</dd></dl>
</dd></dl>
</section>
<section id="event-loop-implementations">
<span id="asyncio-event-loops"></span><h2>事件循环实现<a class="headerlink" href="#event-loop-implementations" title="永久链接至标题"></a></h2>
<p>asyncio 带有两种不同的事件循环实现: <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><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>
<p>默认情况下 asyncio 被配置为在 Unix 上使用 <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> 而在 Windows 上使用 <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>
<dl class="class">
<dt id="asyncio.SelectorEventLoop">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">SelectorEventLoop</code><a class="headerlink" href="#asyncio.SelectorEventLoop" title="永久链接至目标"></a></dt>
<dd><p>基于 <a class="reference internal" href="selectors.html#module-selectors" title="selectors: High-level I/O multiplexing."><code class="xref py py-mod docutils literal notranslate"><span class="pre">selectors</span></code></a> 模块的事件循环。</p>
<p>使用给定平台中最高效的可用 <em>selector</em>。 也可以手动配置要使用的特定 selector:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">selectors</span>
<span class="n">selector</span> <span class="o">=</span> <span class="n">selectors</span><span class="o">.</span><span class="n">SelectSelector</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">SelectorEventLoop</span><span class="p">(</span><span class="n">selector</span><span class="p">)</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">set_event_loop</span><span class="p">(</span><span class="n">loop</span><span class="p">)</span>
</pre></div>
</div>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Unix, Windows。</p>
</dd></dl>
<dl class="class">
<dt id="asyncio.ProactorEventLoop">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">ProactorEventLoop</code><a class="headerlink" href="#asyncio.ProactorEventLoop" title="永久链接至目标"></a></dt>
<dd><p>&quot;I/O Completion Ports&quot; (IOCP) 构建的专为Windows 的事件循环。</p>
<p class="availability"><a class="reference internal" href="intro.html#availability"><span class="std std-ref">可用性</span></a>: Windows。</p>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p><a class="reference external" href="https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports">有关 I/O 完成端口的 MSDN 文档</a></p>
</div>
</dd></dl>
<dl class="class">
<dt id="asyncio.AbstractEventLoop">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">AbstractEventLoop</code><a class="headerlink" href="#asyncio.AbstractEventLoop" title="永久链接至目标"></a></dt>
<dd><p>asyncio 兼容事件循环的抽象基类。</p>
<p><a class="reference internal" href="#asyncio-event-loop"><span class="std std-ref">事件循环方法</span></a> 一节列出了 <code class="docutils literal notranslate"><span class="pre">AbstractEventLoop</span></code> 的替代实现应当定义的所有方法。</p>
</dd></dl>
</section>
<section id="examples">
<h2>例子<a class="headerlink" href="#examples" title="永久链接至标题"></a></h2>
<p>请注意本节中的所有示例都 <strong>有意地</strong> 演示了如何使用低层级的事件循环 API例如 <a class="reference internal" href="#asyncio.loop.run_forever" title="asyncio.loop.run_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.run_forever()</span></code></a><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>。 现代的 asyncio 应用很少需要以这样的方式编写;请考虑使用高层级的函数例如 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">asyncio.run()</span></code></a></p>
<section id="hello-world-with-call-soon">
<span id="asyncio-example-lowlevel-helloworld"></span><h3>call_soon() 的 Hello World 示例。<a class="headerlink" href="#hello-world-with-call-soon" title="永久链接至标题"></a></h3>
<p>一个使用 <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> 方法来安排回调的示例。 回调会显示 <code class="docutils literal notranslate"><span class="pre">&quot;Hello</span> <span class="pre">World&quot;</span></code> 然后停止事件循环:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="k">def</span> <span class="nf">hello_world</span><span class="p">(</span><span class="n">loop</span><span class="p">):</span>
<span class="w"> </span><span class="sd">&quot;&quot;&quot;A callback to print &#39;Hello World&#39; and stop the event loop&quot;&quot;&quot;</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;Hello World&#39;</span><span class="p">)</span>
<span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c1"># Schedule a call to hello_world()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">hello_world</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
<span class="c1"># Blocking call interrupted by loop.stop()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p>一个类似的 <a class="reference internal" href="asyncio-task.html#coroutine"><span class="std std-ref">Hello World</span></a> 示例,使用协程和 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> 函数创建。</p>
</div>
</section>
<section id="display-the-current-date-with-call-later">
<span id="asyncio-example-call-later"></span><h3>使用 call_later() 来展示当前的日期<a class="headerlink" href="#display-the-current-date-with-call-later" title="永久链接至标题"></a></h3>
<p>一个每秒刷新显示当前日期的示例。 回调使用 <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> 方法在 5 秒后将自身重新加入计划日程,然后停止事件循环:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">datetime</span>
<span class="k">def</span> <span class="nf">display_date</span><span class="p">(</span><span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
<span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">end_time</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_later</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">display_date</span><span class="p">,</span> <span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c1"># Schedule the first call to display_date()</span>
<span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">display_date</span><span class="p">,</span> <span class="n">end_time</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
<span class="c1"># Blocking call interrupted by loop.stop()</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<p>一个类似的 <a class="reference internal" href="asyncio-task.html#asyncio-example-sleep"><span class="std std-ref">current date</span></a> 示例,使用协程和 <a class="reference internal" href="asyncio-task.html#asyncio.run" title="asyncio.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> 函数创建。</p>
</div>
</section>
<section id="watch-a-file-descriptor-for-read-events">
<span id="asyncio-example-watch-fd"></span><h3>监控一个文件描述符的读事件<a class="headerlink" href="#watch-a-file-descriptor-for-read-events" title="永久链接至标题"></a></h3>
<p>使用 <a class="reference internal" href="#asyncio.loop.add_reader" title="asyncio.loop.add_reader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_reader()</span></code></a> 方法,等到文件描述符收到一些数据,然后关闭事件循环:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">from</span> <span class="nn">socket</span> <span class="kn">import</span> <span class="n">socketpair</span>
<span class="c1"># Create a pair of connected file descriptors</span>
<span class="n">rsock</span><span class="p">,</span> <span class="n">wsock</span> <span class="o">=</span> <span class="n">socketpair</span><span class="p">()</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">reader</span><span class="p">():</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">rsock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Received:&quot;</span><span class="p">,</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">())</span>
<span class="c1"># We are done: unregister the file descriptor</span>
<span class="n">loop</span><span class="o">.</span><span class="n">remove_reader</span><span class="p">(</span><span class="n">rsock</span><span class="p">)</span>
<span class="c1"># Stop the event loop</span>
<span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>
<span class="c1"># Register the file descriptor for read event</span>
<span class="n">loop</span><span class="o">.</span><span class="n">add_reader</span><span class="p">(</span><span class="n">rsock</span><span class="p">,</span> <span class="n">reader</span><span class="p">)</span>
<span class="c1"># Simulate the reception of data from the network</span>
<span class="n">loop</span><span class="o">.</span><span class="n">call_soon</span><span class="p">(</span><span class="n">wsock</span><span class="o">.</span><span class="n">send</span><span class="p">,</span> <span class="s1">&#39;abc&#39;</span><span class="o">.</span><span class="n">encode</span><span class="p">())</span>
<span class="k">try</span><span class="p">:</span>
<span class="c1"># Run the event loop</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
<span class="c1"># We are done. Close sockets and the event loop.</span>
<span class="n">rsock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">wsock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<ul class="simple">
<li><p>一个类似的 <a class="reference internal" href="asyncio-protocol.html#asyncio-example-create-connection"><span class="std std-ref">示例</span></a>,使用传输、协议和 <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> 方法创建。</p></li>
<li><p>另一个类似的 <a class="reference internal" href="asyncio-stream.html#asyncio-example-create-connection-streams"><span class="std std-ref">示例</span></a>,使用了高层级的 <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">asyncio.open_connection()</span></code></a> 函数和流。</p></li>
</ul>
</div>
</section>
<section id="set-signal-handlers-for-sigint-and-sigterm">
<span id="asyncio-example-unix-signals"></span><h3>为SIGINT和SIGTERM设置信号处理器<a class="headerlink" href="#set-signal-handlers-for-sigint-and-sigterm" title="永久链接至标题"></a></h3>
<p>(这个 <code class="docutils literal notranslate"><span class="pre">signals</span></code> 示例只适用于 Unix。</p>
<p>使用 <a class="reference internal" href="#asyncio.loop.add_signal_handler" title="asyncio.loop.add_signal_handler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.add_signal_handler()</span></code></a> 方法为信号 <code class="xref py py-data docutils literal notranslate"><span class="pre">SIGINT</span></code><code class="xref py py-data docutils literal notranslate"><span class="pre">SIGTERM</span></code> 注册处理程序:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">functools</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">signal</span>
<span class="k">def</span> <span class="nf">ask_exit</span><span class="p">(</span><span class="n">signame</span><span class="p">,</span> <span class="n">loop</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;got signal </span><span class="si">%s</span><span class="s2">: exit&quot;</span> <span class="o">%</span> <span class="n">signame</span><span class="p">)</span>
<span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>
<span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_running_loop</span><span class="p">()</span>
<span class="k">for</span> <span class="n">signame</span> <span class="ow">in</span> <span class="p">{</span><span class="s1">&#39;SIGINT&#39;</span><span class="p">,</span> <span class="s1">&#39;SIGTERM&#39;</span><span class="p">}:</span>
<span class="n">loop</span><span class="o">.</span><span class="n">add_signal_handler</span><span class="p">(</span>
<span class="nb">getattr</span><span class="p">(</span><span class="n">signal</span><span class="p">,</span> <span class="n">signame</span><span class="p">),</span>
<span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">ask_exit</span><span class="p">,</span> <span class="n">signame</span><span class="p">,</span> <span class="n">loop</span><span class="p">))</span>
<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">3600</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Event loop running for 1 hour, press Ctrl+C to interrupt.&quot;</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;pid </span><span class="si">{</span><span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">()</span><span class="si">}</span><span class="s2">: send SIGINT or SIGTERM to exit.&quot;</span><span class="p">)</span>
<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>
</pre></div>
</div>
</section>
</section>
</section>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="../contents.html">目录</a></h3>
<ul>
<li><a class="reference internal" href="#">事件循环</a><ul>
<li><a class="reference internal" href="#event-loop-methods">事件循环方法集</a><ul>
<li><a class="reference internal" href="#running-and-stopping-the-loop">运行和停止循环</a></li>
<li><a class="reference internal" href="#scheduling-callbacks">安排回调</a></li>
<li><a class="reference internal" href="#scheduling-delayed-callbacks">调度延迟回调</a></li>
<li><a class="reference internal" href="#creating-futures-and-tasks">创建 Future 和 Task</a></li>
<li><a class="reference internal" href="#opening-network-connections">打开网络连接</a></li>
<li><a class="reference internal" href="#creating-network-servers">创建网络服务</a></li>
<li><a class="reference internal" href="#transferring-files">传输文件</a></li>
<li><a class="reference internal" href="#tls-upgrade">TLS 升级</a></li>
<li><a class="reference internal" href="#watching-file-descriptors">监控文件描述符</a></li>
<li><a class="reference internal" href="#working-with-socket-objects-directly">直接使用 socket 对象</a></li>
<li><a class="reference internal" href="#dns">DNS</a></li>
<li><a class="reference internal" href="#working-with-pipes">使用管道</a></li>
<li><a class="reference internal" href="#unix-signals">Unix 信号</a></li>
<li><a class="reference internal" href="#executing-code-in-thread-or-process-pools">在线程或者进程池中执行代码。</a></li>
<li><a class="reference internal" href="#error-handling-api">错误处理API</a></li>
<li><a class="reference internal" href="#enabling-debug-mode">开启调试模式</a></li>
<li><a class="reference internal" href="#running-subprocesses">运行子进程</a></li>
</ul>
</li>
<li><a class="reference internal" href="#callback-handles">回调处理</a></li>
<li><a class="reference internal" href="#server-objects">Server 对象</a></li>
<li><a class="reference internal" href="#event-loop-implementations">事件循环实现</a></li>
<li><a class="reference internal" href="#examples">例子</a><ul>
<li><a class="reference internal" href="#hello-world-with-call-soon">call_soon() 的 Hello World 示例。</a></li>
<li><a class="reference internal" href="#display-the-current-date-with-call-later">使用 call_later() 来展示当前的日期</a></li>
<li><a class="reference internal" href="#watch-a-file-descriptor-for-read-events">监控一个文件描述符的读事件</a></li>
<li><a class="reference internal" href="#set-signal-handlers-for-sigint-and-sigterm">为SIGINT和SIGTERM设置信号处理器</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="asyncio-exceptions.html"
title="上一章">异常</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="asyncio-future.html"
title="下一章">Futures</a></p>
<div role="note" aria-label="source link">
<h3>本页</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">报告 Bug</a></li>
<li>
<a href="https://github.com/python/cpython/blob/3.8/Doc/library/asyncio-eventloop.rst"
rel="nofollow">显示源代码
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>导航</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="总目录"
>索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模块索引"
>模块</a> |</li>
<li class="right" >
<a href="asyncio-future.html" title="Futures"
>下一页</a> |</li>
<li class="right" >
<a href="asyncio-exceptions.html" title="异常"
>上一页</a> |</li>
<li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> &#187;</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.8.20 Documentation</a> &#187;
</li>
<li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
<li class="nav-item nav-item-2"><a href="ipc.html" >网络和进程间通信</a> &#187;</li>
<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> --- 异步 I/O</a> &#187;</li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜索" aria-label="快速搜索" type="text" name="q" />
<input type="submit" value="转向" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
|
</li>
</ul>
</div>
<div class="footer">
&copy; <a href="../copyright.html">版权所有</a> 2001-2024, Python Software Foundation.
<br />
This page is licensed under the Python Software Foundation License Version 2.
<br />
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
<br />
<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
<br />
最后更新于 12月 09, 2024.
<a href="https://docs.python.org/3/bugs.html">Found a bug</a>?
<br />
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
</div>
</body>
</html>