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

467 lines
34 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
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>Futures &#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="传输和协议" href="asyncio-protocol.html" />
<link rel="prev" title="事件循环" href="asyncio-eventloop.html" />
<link rel="canonical" href="https://docs.python.org/3/library/asyncio-future.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="#">Futures</a><ul>
<li><a class="reference internal" href="#future-functions">Future 函数</a></li>
<li><a class="reference internal" href="#future-object">Future 对象</a></li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="asyncio-eventloop.html"
title="上一章">事件循环</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="asyncio-protocol.html"
title="下一章">传输和协议</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-future.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-future.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-protocol.html" title="传输和协议"
accesskey="N">下一页</a> |</li>
<li class="right" >
<a href="asyncio-eventloop.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="futures">
<span id="asyncio-futures"></span><h1>Futures<a class="headerlink" href="#futures" title="永久链接至标题"></a></h1>
<p><strong>源代码:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.8/Lib/asyncio/futures.py">Lib/asyncio/futures.py</a>, <a class="reference external" href="https://github.com/python/cpython/tree/3.8/Lib/asyncio/base_futures.py">Lib/asyncio/base_futures.py</a></p>
<hr class="docutils" />
<p><em>Future</em> 对象用来链接 <strong>底层回调式代码</strong> 和高层异步/等待式代码。</p>
<section id="future-functions">
<h2>Future 函数<a class="headerlink" href="#future-functions" title="永久链接至标题"></a></h2>
<dl class="function">
<dt id="asyncio.isfuture">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">isfuture</code><span class="sig-paren">(</span><em class="sig-param">obj</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.isfuture" title="永久链接至目标"></a></dt>
<dd><p>如果 <em>obj</em> 为下面任意对象,返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<ul class="simple">
<li><p>一个 <a class="reference internal" href="#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>一个 <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></li>
<li><p>带有 <code class="docutils literal notranslate"><span class="pre">_asyncio_future_blocking</span></code> 属性的类似 Future 的对象。</p></li>
</ul>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>
<dl class="function">
<dt id="asyncio.ensure_future">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">ensure_future</code><span class="sig-paren">(</span><em class="sig-param">obj</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.ensure_future" title="永久链接至目标"></a></dt>
<dd><p>返回:</p>
<ul class="simple">
<li><p><em>obj</em> 参数会是保持原样,如果 <em>obj</em><a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</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> 或 类似 Future 的对象( <a class="reference internal" href="#asyncio.isfuture" title="asyncio.isfuture"><code class="xref py py-func docutils literal notranslate"><span class="pre">isfuture()</span></code></a> 用于测试。)</p></li>
<li><p>封装了 <em>obj</em><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> 对象,如果 <em>obj</em> 是一个协程 (使用 <a class="reference internal" href="asyncio-task.html#asyncio.iscoroutine" title="asyncio.iscoroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutine()</span></code></a> 进行检测);在此情况下该协程将通过 <code class="docutils literal notranslate"><span class="pre">ensure_future()</span></code> 加入执行计划。</p></li>
<li><p>等待 <em>obj</em><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> 对象,如果 <em>obj</em> 是一个可等待对象( <a class="reference internal" href="inspect.html#inspect.isawaitable" title="inspect.isawaitable"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.isawaitable()</span></code></a> 用于测试)</p></li>
</ul>
<p>如果 <em>obj</em> 不是上述对象会引发一个 <a class="reference internal" href="exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> 异常。</p>
<div class="admonition important">
<p class="admonition-title">重要</p>
<p>查看 <a class="reference internal" href="asyncio-task.html#asyncio.create_task" title="asyncio.create_task"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_task()</span></code></a> 函数,它是创建新任务的首选途径。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5.1 版更改: </span>这个函数接受任意 <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> 对象。</p>
</div>
</dd></dl>
<dl class="function">
<dt id="asyncio.wrap_future">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">wrap_future</code><span class="sig-paren">(</span><em class="sig-param">future</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wrap_future" title="永久链接至目标"></a></dt>
<dd><p>将一个 <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> 对象封装到 <a class="reference internal" href="#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>
</section>
<section id="future-object">
<h2>Future 对象<a class="headerlink" href="#future-object" title="永久链接至标题"></a></h2>
<dl class="class">
<dt id="asyncio.Future">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">Future</code><span class="sig-paren">(</span><em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future" title="永久链接至目标"></a></dt>
<dd><p>一个 Future 代表一个异步运算的最终结果。线程不安全。</p>
<p>Future 是一个 <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> 对象。协程可以等待 Future 对象直到它们有结果或异常集合或被取消。</p>
<p>通常 Future 用于支持底层回调式代码(例如在协议实现中使用asyncio <a class="reference internal" href="asyncio-protocol.html#asyncio-transports-protocols"><span class="std std-ref">transports</span></a>) 与高层异步/等待式代码交互。</p>
<p>经验告诉我们永远不要面向用户的接口暴露 Future 对象,同时建议使用 <a class="reference internal" href="asyncio-eventloop.html#asyncio.loop.create_future" title="asyncio.loop.create_future"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loop.create_future()</span></code></a> 来创建 Future 对象。这种方法可以让 Future 对象使用其它的事件循环实现,它可以注入自己的优化实现。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>加入对 <a class="reference internal" href="contextvars.html#module-contextvars" title="contextvars: Context Variables"><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextvars</span></code></a> 模块的支持。</p>
</div>
<dl class="method">
<dt id="asyncio.Future.result">
<code class="sig-name descname">result</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.result" title="永久链接至目标"></a></dt>
<dd><p>返回 Future 的结果。</p>
<p>如果 Future 状态为 <em>完成</em> ,并由 <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> 方法设置一个结果,则返回这个结果。</p>
<p>如果 Future 状态为 <em>完成</em> ,并由 <a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> 方法设置一个异常,那么这个方法会引发异常。</p>
<p>如果 Future 已 <em>取消</em>,方法会引发一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> 异常。</p>
<p>如果 Future 的结果还不可用,此方法会引发一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> 异常。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.set_result">
<code class="sig-name descname">set_result</code><span class="sig-paren">(</span><em class="sig-param">result</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_result" title="永久链接至目标"></a></dt>
<dd><p>将 Future 标记为 <em>完成</em> 并设置结果。</p>
<p>如果 Future 已经 <em>完成</em> 则抛出一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> 错误。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.set_exception">
<code class="sig-name descname">set_exception</code><span class="sig-paren">(</span><em class="sig-param">exception</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_exception" title="永久链接至目标"></a></dt>
<dd><p>将 Future 标记为 <em>完成</em> 并设置一个异常。</p>
<p>如果 Future 已经 <em>完成</em> 则抛出一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> 错误。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.done">
<code class="sig-name descname">done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.done" title="永久链接至目标"></a></dt>
<dd><p>如果 Future 为已 <em>完成</em> 则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<p>如果 Future 为 <em>取消</em> 或调用 <a class="reference internal" href="#asyncio.Future.set_result" title="asyncio.Future.set_result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_result()</span></code></a> 设置了结果或调用 <a class="reference internal" href="#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_exception()</span></code></a> 设置了异常,那么它就是 <em>完成</em></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.cancelled">
<code class="sig-name descname">cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancelled" title="永久链接至目标"></a></dt>
<dd><p>如果 Future 已 <em>取消</em> 则返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
<p>这个方法通常在设置结果或异常前用来检查 Future 是否已 <em>取消</em></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="ow">not</span> <span class="n">fut</span><span class="o">.</span><span class="n">cancelled</span><span class="p">():</span>
<span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.add_done_callback">
<code class="sig-name descname">add_done_callback</code><span class="sig-paren">(</span><em class="sig-param">callback</em>, <em class="sig-param">*</em>, <em class="sig-param">context=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="永久链接至目标"></a></dt>
<dd><p>添加一个在 Future <em>完成</em> 时运行的回调函数。</p>
<p>调用 <em>callback</em>Future 对象是它的唯一参数。</p>
<p>如果调用这个方法时 Future 已经 <em>完成</em>,回调函数会被 <a class="reference internal" href="asyncio-eventloop.html#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> 调度。</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="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"># Call &#39;print(&quot;Future:&quot;, fut)&#39; when &quot;fut&quot; is done.</span>
<span class="n">fut</span><span class="o">.</span><span class="n">add_done_callback</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;Future:&quot;</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>加入键值类形参 <em>context</em>。请参阅 <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0567"><strong>PEP 567</strong></a> 查看更多细节。</p>
</div>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.remove_done_callback">
<code class="sig-name descname">remove_done_callback</code><span class="sig-paren">(</span><em class="sig-param">callback</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="永久链接至目标"></a></dt>
<dd><p>从回调列表中移除 <em>callback</em></p>
<p>返回被移除的回调函数的数量通常为1除非一个回调函数被添加多次。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.cancel">
<code class="sig-name descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancel" title="永久链接至目标"></a></dt>
<dd><p>取消 Future 并调度回调函数。</p>
<p>如果 Future 已经 <em>完成</em><em>取消</em> ,返回 <code class="docutils literal notranslate"><span class="pre">False</span></code> 。否则将 Future 状态改为 <em>取消</em> 并在调度回调函数后返回 <code class="docutils literal notranslate"><span class="pre">True</span></code></p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.exception">
<code class="sig-name descname">exception</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.exception" title="永久链接至目标"></a></dt>
<dd><p>返回 Future 已设置的异常。</p>
<p>只有 Future 在 <em>完成</em> 时才返回异常(或者 <code class="docutils literal notranslate"><span class="pre">None</span></code> ,如果没有设置异常)。</p>
<p>如果 Future 已 <em>取消</em>,方法会引发一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.CancelledError" title="asyncio.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> 异常。</p>
<p>如果 Future 还没 <em>完成</em> ,这个方法会引发一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> 异常。</p>
</dd></dl>
<dl class="method">
<dt id="asyncio.Future.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.Future.get_loop" title="永久链接至目标"></a></dt>
<dd><p>返回 Future 对象已绑定的事件循环。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.7 新版功能.</span></p>
</div>
</dd></dl>
</dd></dl>
<p id="asyncio-example-future">这个例子创建一个 Future 对象,创建和调度一个异步任务去设置 Future 结果,然后等待其结果:</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">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="n">delay</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="c1"># Sleep for *delay* seconds.</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="n">delay</span><span class="p">)</span>
<span class="c1"># Set *value* as a result of *fut* Future.</span>
<span class="n">fut</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="n">value</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="c1"># Get the current event loop.</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"># Create a new Future object.</span>
<span class="n">fut</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">create_future</span><span class="p">()</span>
<span class="c1"># Run &quot;set_after()&quot; coroutine in a parallel Task.</span>
<span class="c1"># We are using the low-level &quot;loop.create_task()&quot; API here because</span>
<span class="c1"># we already have a reference to the event loop at hand.</span>
<span class="c1"># Otherwise we could have just used &quot;asyncio.create_task()&quot;.</span>
<span class="n">loop</span><span class="o">.</span><span class="n">create_task</span><span class="p">(</span>
<span class="n">set_after</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;... world&#39;</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello ...&#39;</span><span class="p">)</span>
<span class="c1"># Wait until *fut* has a result (1 second) and print it.</span>
<span class="nb">print</span><span class="p">(</span><span class="k">await</span> <span class="n">fut</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>
<div class="admonition important">
<p class="admonition-title">重要</p>
<p>该 Future 对象是为了模仿 <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> 类。主要差异包含:</p>
<ul class="simple">
<li><p>与 asyncio 的 Future 不同,<a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> 实例不是可等待对象。</p></li>
<li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a><a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a> 不接受 <em>timeout</em> 参数。</p></li>
<li><p>Future 没有 <em>完成</em><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.result()</span></code></a><a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.exception()</span></code></a> 抛出一个 <a class="reference internal" href="asyncio-exceptions.html#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a> 异常。</p></li>
<li><p>使用 <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">asyncio.Future.add_done_callback()</span></code></a> 注册的回调函数不会立即调用,而是被 <a class="reference internal" href="asyncio-eventloop.html#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> 调度。</p></li>
<li><p>asyncio Future 不能兼容 <a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.wait()</span></code></a><a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">concurrent.futures.as_completed()</span></code></a> 函数。</p></li>
</ul>
</div>
</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="#">Futures</a><ul>
<li><a class="reference internal" href="#future-functions">Future 函数</a></li>
<li><a class="reference internal" href="#future-object">Future 对象</a></li>
</ul>
</li>
</ul>
<h4>上一个主题</h4>
<p class="topless"><a href="asyncio-eventloop.html"
title="上一章">事件循环</a></p>
<h4>下一个主题</h4>
<p class="topless"><a href="asyncio-protocol.html"
title="下一章">传输和协议</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-future.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-protocol.html" title="传输和协议"
>下一页</a> |</li>
<li class="right" >
<a href="asyncio-eventloop.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>