|
|
第1行: |
第1行: |
| + | {{DISPLAYTITLE:事件循环 — Python 文档}} |
| <div id="event-loop" class="section"> | | <div id="event-loop" class="section"> |
| | | |
− | = Event Loop = | + | = 事件循环 = |
| | | |
− | '''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/asyncio/events.py Lib/asyncio/events.py], | + | '''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/asyncio/events.py`</span>]], |
− | [https://github.com/python/cpython/tree/3.9/Lib/asyncio/base_events.py Lib/asyncio/base_events.py] | + | [[#id3|<span id="id4" class="problematic">:source:`Lib/asyncio/base_events.py`</span>]] |
| | | |
− | Preface
| |
| | | |
− | The event loop is the core of every asyncio application.
| + | ----- |
− | Event loops run asynchronous tasks and callbacks, perform network
| |
− | IO operations, and run subprocesses.
| |
| | | |
− | Application developers should typically use the high-level asyncio functions,
| + | 前言 |
− | such as [[../asyncio-task#asyncio|<code>asyncio.run()</code>]], and should rarely need to reference the loop
| |
− | object or call its methods. This section is intended mostly for authors
| |
− | of lower-level code, libraries, and frameworks, who need finer control over
| |
− | the event loop behavior.
| |
| | | |
− | Obtaining the Event Loop
| + | 事件循环是每个 asyncio 应用程序的核心。 事件循环运行异步任务和回调,执行网络 IO 操作,并运行子进程。 |
| | | |
− | The following low-level functions can be used to get, set, or create
| + | 应用程序开发人员通常应该使用高级 asyncio 函数,例如 [[../asyncio-task#asyncio|asyncio.run()]],并且很少需要引用循环对象或调用其方法。 本节主要面向需要更好地控制事件循环行为的低级代码、库和框架的作者。 |
− | an event loop:
| + | |
| + | 获取事件循环 |
| + | |
| + | 以下低级函数可用于获取、设置或创建事件循环: |
| | | |
| <dl> | | <dl> |
− | <dt><code>asyncio.</code><code>get_running_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">get_running_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Return the running event loop in the current OS thread.</p> | + | <dd><p>返回当前操作系统线程中正在运行的事件循环。</p> |
− | <p>If there is no running event loop a [[../exceptions#RuntimeError|<code>RuntimeError</code>]] is raised. | + | <p>如果没有正在运行的事件循环,则会引发 [[../exceptions#RuntimeError|RuntimeError]]。 此函数只能从协程或回调中调用。</p> |
− | This function can only be called from a coroutine or a callback.</p>
| |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | + | <p><span class="versionmodified added">3.7 版中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>asyncio.</code><code>get_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">get_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Get the current event loop.</p> | + | <dd><p>获取当前事件循环。</p> |
− | <p>If there is no current event loop set in the current OS thread, | + | <p>如果当前操作系统线程中没有设置当前事件循环,操作系统线程是主线程,并且 [[#asyncio.set_event_loop|set_event_loop()]] 尚未被调用,asyncio 将创建一个新的事件循环并将其设置为当前的.</p> |
− | the OS thread is main, and [[#asyncio.set_event_loop|<code>set_event_loop()</code>]] has not yet
| + | <p>由于该函数的行为相当复杂(尤其是在使用自定义事件循环策略时),因此在协程和回调中,使用 [[#asyncio.get_running_loop|get_running_loop()]] 函数优于 [[#asyncio.get_event_loop|get_event_loop()]] 函数。</p> |
− | been called, asyncio will create a new event loop and set it as the
| + | <p>还可以考虑使用 [[../asyncio-task#asyncio|asyncio.run()]] 函数而不是使用较低级别的函数来手动创建和关闭事件循环。</p></dd></dl> |
− | current one.</p>
| |
− | <p>Because this function has rather complex behavior (especially | |
− | when custom event loop policies are in use), using the
| |
− | [[#asyncio.get_running_loop|<code>get_running_loop()</code>]] function is preferred to [[#asyncio.get_event_loop|<code>get_event_loop()</code>]] | |
− | in coroutines and callbacks.</p>
| |
− | <p>Consider also using the [[../asyncio-task#asyncio|<code>asyncio.run()</code>]] function instead of using | |
− | lower level functions to manually create and close an event loop.</p></dd></dl>
| |
| | | |
− | ; <code>asyncio.</code><code>set_event_loop</code><span class="sig-paren">(</span>''<span class="n">loop</span>''<span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">set_event_loop</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">loop</span></span>''<span class="sig-paren">)</span> |
− | : Set ''loop'' as a current event loop for the current OS thread. | + | : 将 ''loop'' 设置为当前 OS 线程的当前事件循环。 |
| | | |
− | ; <code>asyncio.</code><code>new_event_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">new_event_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Create a new event loop object. | + | : 创建一个新的事件循环对象。 |
| | | |
− | Note that the behaviour of [[#asyncio.get_event_loop|<code>get_event_loop()</code>]], [[#asyncio.set_event_loop|<code>set_event_loop()</code>]],
| + | 请注意,[[#asyncio.get_event_loop|get_event_loop()]]、[[#asyncio.set_event_loop|set_event_loop()]] 和 [[#asyncio.new_event_loop|new_event_loop()]] 函数的行为可以通过 设置自定义事件循环策略[ X177X]。 |
− | and [[#asyncio.new_event_loop|<code>new_event_loop()</code>]] functions can be altered by
| |
− | [[../asyncio-policy#asyncio-policies|<span class="std std-ref">setting a custom event loop policy</span>]]. | |
| | | |
− | Contents
| + | 内容 |
| | | |
− | This documentation page contains the following sections:
| + | 此文档页面包含以下部分: |
| | | |
− | * The [[#event-loop-methods|Event Loop Methods]] section is the reference documentation of the event loop APIs; | + | * [[#event-loop-methods|Event Loop Methods]] 部分是事件循环 API 的参考文档; |
− | * The [[#callback-handles|Callback Handles]] section documents the [[#asyncio.Handle|<code>Handle</code>]] and [[#asyncio.TimerHandle|<code>TimerHandle</code>]] instances which are returned from scheduling methods such as [[#asyncio.loop.call_soon|<code>loop.call_soon()</code>]] and [[#asyncio.loop.call_later|<code>loop.call_later()</code>]]; | + | * [[#callback-handles|Callback Handles]] 部分记录了从 [[#asyncio.loop.call_soon|loop.call_soon()]] 和 [[#asyncio.loop.call_later|等调度方法返回的]] [[#asyncio.Handle|Handle]] 和 [[#asyncio.TimerHandle|TimerHandle]] 实例]loop.call_later(); |
− | * The [[#server-objects|Server Objects]] section documents types returned from event loop methods like [[#asyncio.loop.create_server|<code>loop.create_server()</code>]]; | + | * [[#server-objects|Server Objects]] 部分记录了从事件循环方法返回的类型,如 <code>loop.create_server()</code>; |
− | * The [[#event-loop-implementations|Event Loop Implementations]] section documents the [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]] and [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]] classes; | + | * [[#event-loop-implementations|Event Loop Implementations]] 部分记录了 [[#asyncio.SelectorEventLoop|SelectorEventLoop]] 和 [[#asyncio.ProactorEventLoop|ProactorEventLoop]] 类; |
− | * The [[#examples|Examples]] section showcases how to work with some event loop APIs. | + | * [[#examples|Examples]] 部分展示了如何使用一些事件循环 API。 |
| | | |
| <div id="event-loop-methods" class="section"> | | <div id="event-loop-methods" class="section"> |
| | | |
| <span id="asyncio-event-loop"></span> | | <span id="asyncio-event-loop"></span> |
− | == Event Loop Methods == | + | == 事件循环方法 == |
| | | |
− | Event loops have '''low-level''' APIs for the following:
| + | 事件循环具有用于以下内容的 '''低级''' API: |
| | | |
− | <div id="id1" class="contents local topic"> | + | <div id="contents" class="contents local topic"> |
| | | |
− | * [[#running-and-stopping-the-loop|Running and stopping the loop]] | + | * [[#running-and-stopping-the-loop|运行和停止循环]] |
− | * [[#scheduling-callbacks|Scheduling callbacks]] | + | * [[#scheduling-callbacks|调度回调]] |
− | * [[#scheduling-delayed-callbacks|Scheduling delayed callbacks]] | + | * [[#scheduling-delayed-callbacks|调度延迟回调]] |
− | * [[#creating-futures-and-tasks|Creating Futures and Tasks]] | + | * [[#creating-futures-and-tasks|创建期货和任务]] |
− | * [[#opening-network-connections|Opening network connections]] | + | * [[#opening-network-connections|打开网络连接]] |
− | * [[#creating-network-servers|Creating network servers]] | + | * [[#creating-network-servers|创建网络服务器]] |
− | * [[#transferring-files|Transferring files]] | + | * [[#transferring-files|传输文件]] |
− | * [[#tls-upgrade|TLS Upgrade]] | + | * [[#tls-upgrade|TLS 升级]] |
− | * [[#watching-file-descriptors|Watching file descriptors]] | + | * [[#watching-file-descriptors|查看文件描述符]] |
− | * [[#working-with-socket-objects-directly|Working with socket objects directly]] | + | * [[#working-with-socket-objects-directly|直接使用套接字对象]] |
− | * [[#dns|DNS]] | + | * [[#dns|域名系统]] |
− | * [[#working-with-pipes|Working with pipes]] | + | * [[#working-with-pipes|使用管道]] |
− | * [[#unix-signals|Unix signals]] | + | * [[#unix-signals|Unix 信号]] |
− | * [[#executing-code-in-thread-or-process-pools|Executing code in thread or process pools]] | + | * [[#executing-code-in-thread-or-process-pools|在线程或进程池中执行代码]] |
− | * [[#error-handling-api|Error Handling API]] | + | * [[#error-handling-api|错误处理 API]] |
− | * [[#enabling-debug-mode|Enabling debug mode]] | + | * [[#enabling-debug-mode|启用调试模式]] |
− | * [[#running-subprocesses|Running Subprocesses]] | + | * [[#running-subprocesses|运行子进程]] |
| | | |
| | | |
第99行: |
第86行: |
| <div id="running-and-stopping-the-loop" class="section"> | | <div id="running-and-stopping-the-loop" class="section"> |
| | | |
− | === [[#id2|Running and stopping the loop]] === | + | === 运行和停止循环 === |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>run_until_complete</code><span class="sig-paren">(</span>''<span class="n">future</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">run_until_complete</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">future</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Run until the ''future'' (an instance of [[../asyncio-future#asyncio|<code>Future</code>]]) has | + | <dd><p>运行直到 ''future''([[../asyncio-future#asyncio|Future]] 的一个实例)完成。</p> |
− | completed.</p>
| + | <p>如果参数是 [[../asyncio-task#coroutine|协程对象]] ,则它被隐式安排为作为 [[../asyncio-task#asyncio|asyncio.Task]] 运行。</p> |
− | <p>If the argument is a [[../asyncio-task#coroutine|<span class="std std-ref">coroutine object</span>]] it | + | <p>返回 Future 的结果或引发其异常。</p></dd></dl> |
− | is implicitly scheduled to run as a [[../asyncio-task#asyncio|<code>asyncio.Task</code>]].</p>
| |
− | <p>Return the Future's result or raise its exception.</p></dd></dl> | |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>run_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">run_forever</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Run the event loop until [[#asyncio.loop.stop|<code>stop()</code>]] is called.</p> | + | <dd><p>运行事件循环直到 [[#asyncio.loop.stop|stop()]] 被调用。</p> |
− | <p>If [[#asyncio.loop.stop|<code>stop()</code>]] is called before [[#asyncio.loop.run_forever|<code>run_forever()</code>]] is called, | + | <p>如果在调用 [[#asyncio.loop.run_forever|run_forever()]] 之前调用了 [[#asyncio.loop.stop|stop()]],则循环将轮询一次 I/O 选择器,超时为零,运行所有调度以响应 I/ O 事件(以及那些已经安排好的事件),然后退出。</p> |
− | the loop will poll the I/O selector once with a timeout of zero,
| + | <p>如果在 [[#asyncio.loop.run_forever|run_forever()]] 运行时调用 [[#asyncio.loop.stop|stop()]],则循环将运行当前批次的回调,然后退出。 请注意,在这种情况下,回调安排的新回调将不会运行; 相反,它们将在下次调用 [[#asyncio.loop.run_forever|run_forever()]] 或 [[#asyncio.loop.run_until_complete|run_until_complete()]] 时运行。</p></dd></dl> |
− | run all callbacks scheduled in response to I/O events (and
| |
− | those that were already scheduled), and then exit.</p>
| |
− | <p>If [[#asyncio.loop.stop|<code>stop()</code>]] is called while [[#asyncio.loop.run_forever|<code>run_forever()</code>]] is running, | |
− | the loop will run the current batch of callbacks and then exit.
| |
− | Note that new callbacks scheduled by callbacks will not run in this
| |
− | case; instead, they will run the next time [[#asyncio.loop.run_forever|<code>run_forever()</code>]] or
| |
− | [[#asyncio.loop.run_until_complete|<code>run_until_complete()</code>]] is called.</p></dd></dl> | |
| | | |
− | ; <code>loop.</code><code>stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">stop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Stop the event loop. | + | : 停止事件循环。 |
| | | |
− | ; <code>loop.</code><code>is_running</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">is_running</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Return <code>True</code> if the event loop is currently running. | + | : 如果事件循环当前正在运行,则返回 <code>True</code>。 |
| | | |
− | ; <code>loop.</code><code>is_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">is_closed</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Return <code>True</code> if the event loop was closed. | + | : 如果事件循环已关闭,则返回 <code>True</code>。 |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>close</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Close the event loop.</p>
| + | <dd><p>关闭事件循环。</p> |
− | <p>The loop must not be running when this function is called.
| + | <p>调用此函数时,循环不能运行。 任何挂起的回调都将被丢弃。</p> |
− | Any pending callbacks will be discarded.</p>
| + | <p>此方法清除所有队列并关闭执行程序,但不等待执行程序完成。</p> |
− | <p>This method clears all queues and shuts down the executor, but does
| + | <p>这种方法是幂等的且不可逆的。 事件循环关闭后不应调用其他方法。</p></dd></dl> |
− | not wait for the executor to finish.</p>
| |
− | <p>This method is idempotent and irreversible. No other methods
| |
− | should be called after the event loop is closed.</p></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>shutdown_asyncgens</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
| |
− | <dd><p>Schedule all currently open [[../../glossary#term-asynchronous-generator|<span class="xref std std-term">asynchronous generator</span>]] objects to
| |
− | close with an [[../../reference/expressions#agen|<code>aclose()</code>]] call. After calling this method, | |
− | the event loop will issue a warning if a new asynchronous generator
| |
− | is iterated. This should be used to reliably finalize all scheduled
| |
− | asynchronous generators.</p>
| |
− | <p>Note that there is no need to call this function when | |
− | [[../asyncio-task#asyncio|<code>asyncio.run()</code>]] is used.</p>
| |
− | <p>Example:</p>
| |
− | <div class="highlight-python3 notranslate">
| |
− | | |
− | <div class="highlight">
| |
− | | |
− | <pre>try:
| |
− | loop.run_forever()
| |
− | finally:
| |
− | loop.run_until_complete(loop.shutdown_asyncgens())
| |
− | loop.close()</pre>
| |
− | | |
− | </div>
| |
− | | |
− | </div>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.6 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>shutdown_default_executor</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
| |
− | <dd><p>Schedule the closure of the default executor and wait for it to join all of | |
− | the threads in the <code>ThreadPoolExecutor</code>. After calling this method, a
| |
− | [[../exceptions#RuntimeError|<code>RuntimeError</code>]] will be raised if [[#asyncio.loop.run_in_executor|<code>loop.run_in_executor()</code>]] is called
| |
− | while using the default executor.</p>
| |
− | <p>Note that there is no need to call this function when | |
− | [[../asyncio-task#asyncio|<code>asyncio.run()</code>]] is used.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.9 新版功能.</span></p> | |
− | | |
− | </div></dd></dl>
| |
| | | |
| | | |
第188行: |
第120行: |
| <div id="scheduling-callbacks" class="section"> | | <div id="scheduling-callbacks" class="section"> |
| | | |
− | === [[#id3|Scheduling callbacks]] === | + | === 调度回调 === |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>call_soon</code><span class="sig-paren">(</span>''<span class="n">callback</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_soon</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Schedule the ''callback'' [[../../glossary#term-callback|<span class="xref std std-term">callback</span>]] to be called with | + | <dd><p>安排在事件循环的下一次迭代中使用 ''args'' 参数调用 ''callback'' [[../../glossary#term-callback|callback]]。</p> |
− | ''args'' arguments at the next iteration of the event loop.</p>
| + | <p>回调按注册的顺序调用。 每个回调只会被调用一次。</p> |
− | <p>Callbacks are called in the order in which they are registered. | + | <p>一个可选的仅关键字 ''context'' 参数允许为 ''callback'' 指定自定义 [[../contextvars#contextvars|contextvars.Context]] 以运行。 当没有提供 ''context'' 时使用当前上下文。</p> |
− | Each callback will be called exactly once.</p>
| + | <p>返回一个 [[#asyncio.Handle|asyncio.Handle]] 的实例,稍后可以使用它来取消回调。</p> |
− | <p>An optional keyword-only ''context'' argument allows specifying a | + | <p>此方法不是线程安全的。</p></dd></dl> |
− | custom [[../contextvars#contextvars|<code>contextvars.Context</code>]] for the ''callback'' to run in.
| |
− | The current context is used when no ''context'' is provided.</p>
| |
− | <p>An instance of [[#asyncio.Handle|<code>asyncio.Handle</code>]] is returned, which can be | |
− | used later to cancel the callback.</p>
| |
− | <p>This method is not thread-safe.</p></dd></dl> | |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>call_soon_threadsafe</code><span class="sig-paren">(</span>''<span class="n">callback</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_soon_threadsafe</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>A thread-safe variant of [[#asyncio.loop.call_soon|<code>call_soon()</code>]]. Must be used to | + | <dd><p>[[#asyncio.loop.call_soon|call_soon()]] 的线程安全变体。 必须用于从另一个线程 ''调度回调'' 。</p> |
− | schedule callbacks ''from another thread''.</p>
| + | <p>如果在已关闭的循环上调用,则引发 [[../exceptions#RuntimeError|RuntimeError]]。 当主应用程序关闭时,这可能发生在辅助线程上。</p> |
− | <p>See the [[../asyncio-dev#asyncio-multithreading|<span class="std std-ref">concurrency and multithreading</span>]] | + | <p>请参阅文档的 [[../asyncio-dev#asyncio-multithreading|并发和多线程]] 部分。</p></dd></dl> |
− | section of the documentation.</p></dd></dl>
| |
| | | |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <span class="versionmodified changed">在 3.7 版更改: </span>The ''context'' keyword-only parameter was added. See <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0567 '''PEP 567'''] | + | <span class="versionmodified changed"> 3.7 版更改: </span> 添加了 ''context'' 仅关键字参数。 有关更多详细信息,请参阅 <span id="index-0" class="target"></span>[https://www.python.org/dev/peps/pep-0567 PEP 567]。 |
− | for more details.
| |
| | | |
| | | |
第219行: |
第144行: |
| <div id="asyncio-pass-keywords" class="admonition note"> | | <div id="asyncio-pass-keywords" class="admonition note"> |
| | | |
− | 注解
| + | 笔记 |
| | | |
− | Most [[../asyncio#module-asyncio|<code>asyncio</code>]] scheduling functions don't allow passing
| + | 大多数 [[../asyncio#module-asyncio|asyncio]] 调度函数不允许传递关键字参数。 为此,请使用 [[../functools#functools|functools.partial()]]: |
− | keyword arguments. To do that, use [[../functools#functools|<code>functools.partial()</code>]]:
| |
| | | |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
第228行: |
第152行: |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre># will schedule "print("Hello", flush=True)" | + | <syntaxhighlight lang="python3"># will schedule "print("Hello", flush=True)" |
| loop.call_soon( | | loop.call_soon( |
− | functools.partial(print, "Hello", flush=True))</pre> | + | functools.partial(print, "Hello", flush=True))</syntaxhighlight> |
| | | |
| </div> | | </div> |
| | | |
| </div> | | </div> |
− | Using partial objects is usually more convenient than using lambdas,
| + | 使用部分对象通常比使用 lambda 更方便,因为 asyncio 可以在调试和错误消息中更好地呈现部分对象。 |
− | as asyncio can render partial objects better in debug and error
| |
− | messages.
| |
| | | |
| | | |
第246行: |
第168行: |
| | | |
| <span id="asyncio-delayed-calls"></span> | | <span id="asyncio-delayed-calls"></span> |
− | === [[#id4|Scheduling delayed callbacks]] === | + | === 调度延迟回调 === |
| | | |
− | Event loop provides mechanisms to schedule callback functions
| + | 事件循环提供了安排回调函数在未来某个时间点调用的机制。 事件循环使用单调时钟来跟踪时间。 |
− | to be called at some point in the future. Event loop uses monotonic
| |
− | clocks to track time.
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>call_later</code><span class="sig-paren">(</span>''<span class="n">delay</span>'', ''<span class="n">callback</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_later</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">delay</span></span>'', ''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Schedule ''callback'' to be called after the given ''delay'' | + | <dd><p>安排 ''callback'' 在给定的 ''delay'' 秒数(可以是 int 或 float)后调用。</p> |
− | number of seconds (can be either an int or a float).</p>
| + | <p>返回 [[#asyncio.TimerHandle|asyncio.TimerHandle]] 的实例,可用于取消回调。</p> |
− | <p>An instance of [[#asyncio.TimerHandle|<code>asyncio.TimerHandle</code>]] is returned which can | + | <p>''callback'' 只会被调用一次。 如果两个回调被安排在完全相同的时间,则调用它们的顺序是不确定的。</p> |
− | be used to cancel the callback.</p>
| + | <p>可选的位置 ''args'' 将在调用时传递给回调。 如果您希望使用关键字参数调用回调,请使用 [[../functools#functools|functools.partial()]]。</p> |
− | <p>''callback'' will be called exactly once. If two callbacks are | + | <p>一个可选的仅关键字 ''context'' 参数允许为 ''callback'' 指定自定义 [[../contextvars#contextvars|contextvars.Context]] 以运行。 当没有提供 ''context'' 时使用当前上下文。</p> |
− | scheduled for exactly the same time, the order in which they
| |
− | are called is undefined.</p>
| |
− | <p>The optional positional ''args'' will be passed to the callback when | |
− | it is called. If you want the callback to be called with keyword
| |
− | arguments use [[../functools#functools|<code>functools.partial()</code>]].</p>
| |
− | <p>An optional keyword-only ''context'' argument allows specifying a | |
− | custom [[../contextvars#contextvars|<code>contextvars.Context</code>]] for the ''callback'' to run in.
| |
− | The current context is used when no ''context'' is provided.</p>
| |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>The ''context'' keyword-only parameter was added. See <span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0567 '''PEP 567'''] | + | <p><span class="versionmodified changed"> 3.7 版更改: </span> 添加了 ''context'' 仅关键字参数。 有关更多详细信息,请参阅 <span id="index-1" class="target"></span>[https://www.python.org/dev/peps/pep-0567 PEP 567]。</p> |
− | for more details.</p>
| |
| | | |
| </div> | | </div> |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.8 版更改: </span>In Python 3.7 and earlier with the default event loop implementation, | + | <p><span class="versionmodified changed"> 3.8 版更改: </span> 在 Python 3.7 及更早版本中,使用默认事件循环实现, ''延迟'' 不能超过 1 天。 这已在 Python 3.8 中修复。</p> |
− | the ''delay'' could not exceed one day.
| |
− | This has been fixed in Python 3.8.</p>
| |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>call_at</code><span class="sig-paren">(</span>''<span class="n">when</span>'', ''<span class="n">callback</span>'', ''<span class="o">*</span><span class="n">args</span>'', ''<span class="n">context</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_at</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">when</span></span>'', ''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>'', ''<span class="n"><span class="pre">context</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Schedule ''callback'' to be called at the given absolute timestamp | + | <dd><p>安排 ''callback'' 在给定的绝对时间戳 ''when''(整数或浮点数)上调用,使用与 [[#asyncio.loop.time|loop.time()]] 相同的时间参考。</p> |
− | ''when'' (an int or a float), using the same time reference as | + | <p>此方法的行为与 [[#asyncio.loop.call_later|call_later()]] 相同。</p> |
− | [[#asyncio.loop.time|<code>loop.time()</code>]].</p> | + | <p>返回 [[#asyncio.TimerHandle|asyncio.TimerHandle]] 的实例,可用于取消回调。</p> |
− | <p>This method's behavior is the same as [[#asyncio.loop.call_later|<code>call_later()</code>]].</p> | |
− | <p>An instance of [[#asyncio.TimerHandle|<code>asyncio.TimerHandle</code>]] is returned which can | |
− | be used to cancel the callback.</p>
| |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>The ''context'' keyword-only parameter was added. See <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0567 '''PEP 567'''] | + | <p><span class="versionmodified changed"> 3.7 版更改: </span> 添加了 ''context'' 仅关键字参数。 有关更多详细信息,请参阅 <span id="index-2" class="target"></span>[https://www.python.org/dev/peps/pep-0567 PEP 567]。</p> |
− | for more details.</p>
| |
| | | |
| </div> | | </div> |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.8 版更改: </span>In Python 3.7 and earlier with the default event loop implementation, | + | <p><span class="versionmodified changed"> 3.8 版更改: </span> 在 Python 3.7 及更早版本中,默认事件循环实现,''when'' 与当前时间之间的差异不能超过一天。 这已在 Python 3.8 中修复。</p> |
− | the difference between ''when'' and the current time could not exceed
| |
− | one day. This has been fixed in Python 3.8.</p>
| |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
− | ; <code>loop.</code><code>time</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">time</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Return the current time, as a [[../functions#float|<code>float</code>]] value, according to the event loop's internal monotonic clock. | + | : 根据事件循环的内部单调时钟返回当前时间,作为 [[../functions#float|float]] 值。 |
| | | |
| <div class="admonition note"> | | <div class="admonition note"> |
| | | |
− | 注解
| + | 笔记 |
| | | |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <span class="versionmodified changed">在 3.8 版更改: </span>In Python 3.7 and earlier timeouts (relative ''delay'' or absolute ''when'') | + | <span class="versionmodified changed"> 3.8 版更改: </span> 在 Python 3.7 及更早版本中,超时(相对 ''延迟'' 或绝对 ''when'' )不应超过 1 天。 这已在 Python 3.8 中修复。 |
− | should not exceed one day. This has been fixed in Python 3.8.
| |
| | | |
| | | |
第321行: |
第223行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | The [[../asyncio-task#asyncio|<code>asyncio.sleep()</code>]] function.
| + | <code>asyncio.sleep()</code> 功能。 |
| | | |
| | | |
第331行: |
第233行: |
| <div id="creating-futures-and-tasks" class="section"> | | <div id="creating-futures-and-tasks" class="section"> |
| | | |
− | === [[#id5|Creating Futures and Tasks]] === | + | === 创建期货和任务 === |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>create_future</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_future</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Create an [[../asyncio-future#asyncio|<code>asyncio.Future</code>]] object attached to the event loop.</p> | + | <dd><p>创建一个附加到事件循环的 [[../asyncio-future#asyncio|asyncio.Future]] 对象。</p> |
− | <p>This is the preferred way to create Futures in asyncio. This lets | + | <p>这是在 asyncio 中创建 Futures 的首选方式。 这让第三方事件循环提供 Future 对象的替代实现(具有更好的性能或检测)。</p> |
− | third-party event loops provide alternative implementations of
| |
− | the Future object (with better performance or instrumentation).</p>
| |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.5.2 新版功能.</span></p> | + | <p><span class="versionmodified added">版本 3.5.2 中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>create_task</code><span class="sig-paren">(</span>''coro'', ''\*'', ''name=None''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">create_task</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">coro</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Schedule the execution of a [[../asyncio-task#coroutine|<span class="std std-ref">Coroutines</span>]]. | + | <dd><p>安排 [[../asyncio-task#coroutine|协程]] 的执行。 返回一个 [[../asyncio-task#asyncio|Task]] 对象。</p> |
− | Return a [[../asyncio-task#asyncio|<code>Task</code>]] object.</p>
| + | <p>第三方事件循环可以使用它们自己的 [[../asyncio-task#asyncio|Task]] 子类来实现互操作性。 在这种情况下,结果类型是 [[../asyncio-task#asyncio|Task]] 的子类。</p> |
− | <p>Third-party event loops can use their own subclass of [[../asyncio-task#asyncio|<code>Task</code>]] | + | <p>如果提供了 ''name'' 参数而不是 <code>None</code>,则使用 [[../asyncio-task#asyncio.Task|Task.set_name()]] 将其设置为任务的名称。</p> |
− | for interoperability. In this case, the result type is a subclass
| |
− | of [[../asyncio-task#asyncio|<code>Task</code>]].</p>
| |
− | <p>If the ''name'' argument is provided and not <code>None</code>, it is set as | |
− | the name of the task using [[../asyncio-task#asyncio.Task|<code>Task.set_name()</code>]].</p>
| |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.8 版更改: </span>Added the <code>name</code> parameter.</p> | + | <p><span class="versionmodified changed"> 3.8 版变更: </span> 增加了 <code>name</code> 参数。</p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>set_task_factory</code><span class="sig-paren">(</span>''<span class="n">factory</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">set_task_factory</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">factory</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Set a task factory that will be used by | + | <dd><p>设置一个由 [[#asyncio.loop.create_task|loop.create_task()]] 使用的任务工厂。</p> |
− | [[#asyncio.loop.create_task|<code>loop.create_task()</code>]].</p> | + | <p>如果 ''factory'' 是 <code>None</code> 将设置默认任务工厂。 否则,''factory'' 必须是一个 ''callable'',签名匹配 <code>(loop, coro)</code>,其中 ''loop'' 是对活动事件循环的引用,而 '']coro'' 是一个协程对象。 可调用对象必须返回 [[../asyncio-future#asyncio|asyncio.Future]] 兼容对象。</p></dd></dl> |
− | <p>If ''factory'' is <code>None</code> the default task factory will be set. | |
− | Otherwise, ''factory'' must be a ''callable'' with the signature matching
| |
− | <code>(loop, coro)</code>, where ''loop'' is a reference to the active | |
− | event loop, and ''coro'' is a coroutine object. The callable
| |
− | must return a [[../asyncio-future#asyncio|<code>asyncio.Future</code>]]-compatible object.</p></dd></dl>
| |
| | | |
− | ; <code>loop.</code><code>get_task_factory</code><span class="sig-paren">(</span><span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">get_task_factory</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span> |
− | : Return a task factory or <code>None</code> if the default one is in use. | + | : 如果使用默认工厂,则返回任务工厂或 <code>None</code>。 |
| | | |
| | | |
第377行: |
第268行: |
| <div id="opening-network-connections" class="section"> | | <div id="opening-network-connections" class="section"> |
| | | |
− | === [[#id6|Opening network connections]] === | + | === 打开网络连接 === |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>create_connection</code><span class="sig-paren">(</span>''protocol_factory'', ''host=None'', ''port=None'', ''\*'', ''ssl=None'', ''family=0'', ''proto=0'', ''flags=0'', ''sock=None'', ''local_addr=None'', ''server_hostname=None'', ''ssl_handshake_timeout=None'', ''happy_eyeballs_delay=None'', ''interleave=None''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Open a streaming transport connection to a given
| |
− | address specified by ''host'' and ''port''.</p>
| |
− | <p>The socket family can be either [[../socket#socket|<code>AF_INET</code>]] or
| |
− | [[../socket#socket|<code>AF_INET6</code>]] depending on ''host'' (or the ''family''
| |
− | argument, if provided).</p>
| |
− | <p>The socket type will be [[../socket#socket|<code>SOCK_STREAM</code>]].</p>
| |
− | <p>''protocol_factory'' must be a callable returning an
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">asyncio protocol</span>]] implementation.</p>
| |
− | <p>This method will try to establish the connection in the background.
| |
− | When successful, it returns a <code>(transport, protocol)</code> pair.</p>
| |
− | <p>The chronological synopsis of the underlying operation is as follows:</p>
| |
− | <ol>
| |
− | <li><p>The connection is established and a [[../asyncio-protocol#asyncio-transport|<span class="std std-ref">transport</span>]]
| |
− | is created for it.</p></li>
| |
− | <li><p>''protocol_factory'' is called without arguments and is expected to
| |
− | return a [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">protocol</span>]] instance.</p></li>
| |
− | <li><p>The protocol instance is coupled with the transport by calling its
| |
− | [[../asyncio-protocol#asyncio.BaseProtocol|<code>connection_made()</code>]] method.</p></li>
| |
− | <li><p>A <code>(transport, protocol)</code> tuple is returned on success.</p></li></ol>
| |
− | | |
− | <p>The created transport is an implementation-dependent bidirectional
| |
− | stream.</p>
| |
− | <p>Other arguments:</p>
| |
− | <ul>
| |
− | <li><p>''ssl'': if given and not false, a SSL/TLS transport is created
| |
− | (by default a plain TCP transport is created). If ''ssl'' is
| |
− | a [[../ssl#ssl|<code>ssl.SSLContext</code>]] object, this context is used to create
| |
− | the transport; if ''ssl'' is [[../constants#True|<code>True</code>]], a default context returned
| |
− | from [[../ssl#ssl|<code>ssl.create_default_context()</code>]] is used.</p>
| |
− | <div class="admonition seealso">
| |
− | | |
− | <p>参见</p>
| |
− | <p>[[../ssl#ssl-security|<span class="std std-ref">SSL/TLS security considerations</span>]]</p>
| |
− | | |
− | </div></li>
| |
− | <li><p>''server_hostname'' sets or overrides the hostname that the target
| |
− | server's certificate will be matched against. Should only be passed
| |
− | if ''ssl'' is not <code>None</code>. By default the value of the ''host'' argument
| |
− | is used. If ''host'' is empty, there is no default and you must pass a
| |
− | value for ''server_hostname''. If ''server_hostname'' is an empty
| |
− | string, hostname matching is disabled (which is a serious security
| |
− | risk, allowing for potential man-in-the-middle attacks).</p></li>
| |
− | <li><p>''family'', ''proto'', ''flags'' are the optional address family, protocol
| |
− | and flags to be passed through to getaddrinfo() for ''host'' resolution.
| |
− | If given, these should all be integers from the corresponding
| |
− | [[../socket#module-socket|<code>socket</code>]] module constants.</p></li>
| |
− | <li><p>''happy_eyeballs_delay'', if given, enables Happy Eyeballs for this
| |
− | connection. It should
| |
− | be a floating-point number representing the amount of time in seconds
| |
− | to wait for a connection attempt to complete, before starting the next
| |
− | attempt in parallel. This is the "Connection Attempt Delay" as defined
| |
− | in <span id="index-3" class="target"></span>[https://tools.ietf.org/html/rfc8305.html '''RFC 8305''']. A sensible default value recommended by the RFC is <code>0.25</code>
| |
− | (250 milliseconds).</p></li>
| |
− | <li><p>''interleave'' controls address reordering when a host name resolves to
| |
− | multiple IP addresses.
| |
− | If <code>0</code> or unspecified, no reordering is done, and addresses are
| |
− | tried in the order returned by [[#asyncio.loop.getaddrinfo|<code>getaddrinfo()</code>]]. If a positive integer
| |
− | is specified, the addresses are interleaved by address family, and the
| |
− | given integer is interpreted as "First Address Family Count" as defined
| |
− | in <span id="index-4" class="target"></span>[https://tools.ietf.org/html/rfc8305.html '''RFC 8305''']. The default is <code>0</code> if ''happy_eyeballs_delay'' is not
| |
− | specified, and <code>1</code> if it is.</p></li>
| |
− | <li><p>''sock'', if given, should be an existing, already connected
| |
− | [[../socket#socket|<code>socket.socket</code>]] object to be used by the transport.
| |
− | If ''sock'' is given, none of ''host'', ''port'', ''family'', ''proto'', ''flags'',
| |
− | ''happy_eyeballs_delay'', ''interleave''
| |
− | and ''local_addr'' should be specified.</p></li>
| |
− | <li><p>''local_addr'', if given, is a <code>(local_host, local_port)</code> tuple used
| |
− | to bind the socket to locally. The ''local_host'' and ''local_port''
| |
− | are looked up using <code>getaddrinfo()</code>, similarly to ''host'' and ''port''.</p></li>
| |
− | <li><p>''ssl_handshake_timeout'' is (for a TLS connection) the time in seconds
| |
− | to wait for the TLS handshake to complete before aborting the connection.
| |
− | <code>60.0</code> seconds if <code>None</code> (default).</p></li></ul>
| |
− | | |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.8 新版功能: </span>Added the ''happy_eyeballs_delay'' and ''interleave'' parameters.</p>
| |
− | <p>Happy Eyeballs Algorithm: Success with Dual-Stack Hosts.
| |
− | When a server's IPv4 path and protocol are working, but the server's
| |
− | IPv6 path and protocol are not working, a dual-stack client
| |
− | application experiences significant connection delay compared to an
| |
− | IPv4-only client. This is undesirable because it causes the dual-
| |
− | stack client to have a worse user experience. This document
| |
− | specifies requirements for algorithms that reduce this user-visible
| |
− | delay and provides an algorithm.</p>
| |
− | <p>For more information: https://tools.ietf.org/html/rfc6555</p>
| |
− | | |
− | </div>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能: </span>The ''ssl_handshake_timeout'' parameter.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.6 版更改: </span>The socket option <code>TCP_NODELAY</code> is set by default
| |
− | for all TCP connections.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.5 版更改: </span>Added support for SSL/TLS in [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]].</p>
| |
− | | |
− | </div>
| |
− | <div class="admonition seealso">
| |
− | | |
− | <p>参见</p>
| |
− | <p>The [[../asyncio-stream#asyncio|<code>open_connection()</code>]] function is a high-level alternative
| |
− | API. It returns a pair of ([[../asyncio-stream#asyncio|<code>StreamReader</code>]], [[../asyncio-stream#asyncio|<code>StreamWriter</code>]])
| |
− | that can be used directly in async/await code.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>create_datagram_endpoint</code><span class="sig-paren">(</span>''protocol_factory'', ''local_addr=None'', ''remote_addr=None'', ''\*'', ''family=0'', ''proto=0'', ''flags=0'', ''reuse_address=None'', ''reuse_port=None'', ''allow_broadcast=None'', ''sock=None''<span class="sig-paren">)</span></dt>
| |
− | <dd><div class="admonition note">
| |
− | | |
− | <p>注解</p>
| |
− | <p>The parameter ''reuse_address'' is no longer supported, as using
| |
− | <code>SO_REUSEADDR</code> poses a significant security concern for
| |
− | UDP. Explicitly passing <code>reuse_address=True</code> will raise an exception.</p>
| |
− | <p>When multiple processes with differing UIDs assign sockets to an
| |
− | identical UDP socket address with <code>SO_REUSEADDR</code>, incoming packets can
| |
− | become randomly distributed among the sockets.</p>
| |
− | <p>For supported platforms, ''reuse_port'' can be used as a replacement for
| |
− | similar functionality. With ''reuse_port'',
| |
− | <code>SO_REUSEPORT</code> is used instead, which specifically
| |
− | prevents processes with differing UIDs from assigning sockets to the same
| |
− | socket address.</p>
| |
− | | |
− | </div>
| |
− | <p>Create a datagram connection.</p>
| |
− | <p>The socket family can be either [[../socket#socket|<code>AF_INET</code>]],
| |
− | [[../socket#socket|<code>AF_INET6</code>]], or [[../socket#socket|<code>AF_UNIX</code>]],
| |
− | depending on ''host'' (or the ''family'' argument, if provided).</p>
| |
− | <p>The socket type will be [[../socket#socket|<code>SOCK_DGRAM</code>]].</p>
| |
− | <p>''protocol_factory'' must be a callable returning a
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">protocol</span>]] implementation.</p>
| |
− | <p>A tuple of <code>(transport, protocol)</code> is returned on success.</p>
| |
− | <p>Other arguments:</p>
| |
− | <ul>
| |
− | <li><p>''local_addr'', if given, is a <code>(local_host, local_port)</code> tuple used
| |
− | to bind the socket to locally. The ''local_host'' and ''local_port''
| |
− | are looked up using [[#asyncio.loop.getaddrinfo|<code>getaddrinfo()</code>]].</p></li>
| |
− | <li><p>''remote_addr'', if given, is a <code>(remote_host, remote_port)</code> tuple used
| |
− | to connect the socket to a remote address. The ''remote_host'' and
| |
− | ''remote_port'' are looked up using [[#asyncio.loop.getaddrinfo|<code>getaddrinfo()</code>]].</p></li>
| |
− | <li><p>''family'', ''proto'', ''flags'' are the optional address family, protocol
| |
− | and flags to be passed through to [[#asyncio.loop.getaddrinfo|<code>getaddrinfo()</code>]] for ''host''
| |
− | resolution. If given, these should all be integers from the
| |
− | corresponding [[../socket#module-socket|<code>socket</code>]] module constants.</p></li>
| |
− | <li><p>''reuse_port'' tells the kernel to allow this endpoint to be bound to the
| |
− | same port as other existing endpoints are bound to, so long as they all
| |
− | set this flag when being created. This option is not supported on Windows
| |
− | and some Unixes. If the <code>SO_REUSEPORT</code> constant is not
| |
− | defined then this capability is unsupported.</p></li>
| |
− | <li><p>''allow_broadcast'' tells the kernel to allow this endpoint to send
| |
− | messages to the broadcast address.</p></li>
| |
− | <li><p>''sock'' can optionally be specified in order to use a preexisting,
| |
− | already connected, [[../socket#socket|<code>socket.socket</code>]] object to be used by the
| |
− | transport. If specified, ''local_addr'' and ''remote_addr'' should be omitted
| |
− | (must be [[../constants#None|<code>None</code>]]).</p></li></ul>
| |
− | | |
− | <p>See [[../asyncio-protocol#asyncio-udp-echo-client-protocol|<span class="std std-ref">UDP echo client protocol</span>]] and
| |
− | [[../asyncio-protocol#asyncio-udp-echo-server-protocol|<span class="std std-ref">UDP echo server protocol</span>]] examples.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.4.4 版更改: </span>The ''family'', ''proto'', ''flags'', ''reuse_address'', ''reuse_port,
| |
− | *allow_broadcast'', and ''sock'' parameters were added.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.8.1 版更改: </span>The ''reuse_address'' parameter is no longer supported due to security
| |
− | concerns.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.8 版更改: </span>Added support for Windows.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>create_unix_connection</code><span class="sig-paren">(</span>''protocol_factory'', ''path=None'', ''\*'', ''ssl=None'', ''sock=None'', ''server_hostname=None'', ''ssl_handshake_timeout=None''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Create a Unix connection.</p>
| |
− | <p>The socket family will be [[../socket#socket|<code>AF_UNIX</code>]]; socket
| |
− | type will be [[../socket#socket|<code>SOCK_STREAM</code>]].</p>
| |
− | <p>A tuple of <code>(transport, protocol)</code> is returned on success.</p>
| |
− | <p>''path'' is the name of a Unix domain socket and is required,
| |
− | unless a ''sock'' parameter is specified. Abstract Unix sockets,
| |
− | [[../stdtypes#str|<code>str</code>]], [[../stdtypes#bytes|<code>bytes</code>]], and [[../pathlib#pathlib|<code>Path</code>]] paths are
| |
− | supported.</p>
| |
− | <p>See the documentation of the [[#asyncio.loop.create_connection|<code>loop.create_connection()</code>]] method
| |
− | for information about arguments to this method.</p>
| |
− | <p>[[../intro#availability|<span class="std std-ref">Availability</span>]]: Unix.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能: </span>The ''ssl_handshake_timeout'' parameter.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>The ''path'' parameter can now be a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
| |
− | | |
− | </div></dd></dl>
| |
| | | |
| | | |
第591行: |
第274行: |
| <div id="creating-network-servers" class="section"> | | <div id="creating-network-servers" class="section"> |
| | | |
− | === [[#id7|Creating network servers]] === | + | === 创建网络服务器 === |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>create_server</code><span class="sig-paren">(</span>''protocol_factory'', ''host=None'', ''port=None'', ''\*'', ''family=socket.AF_UNSPEC'', ''flags=socket.AI_PASSIVE'', ''sock=None'', ''backlog=100'', ''ssl=None'', ''reuse_address=None'', ''reuse_port=None'', ''ssl_handshake_timeout=None'', ''start_serving=True''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Create a TCP server (socket type [[../socket#socket|<code>SOCK_STREAM</code>]]) listening
| |
− | on ''port'' of the ''host'' address.</p>
| |
− | <p>Returns a [[#asyncio.Server|<code>Server</code>]] object.</p>
| |
− | <p>Arguments:</p>
| |
− | <ul>
| |
− | <li><p>''protocol_factory'' must be a callable returning a
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">protocol</span>]] implementation.</p></li>
| |
− | <li><p>The ''host'' parameter can be set to several types which determine where
| |
− | the server would be listening:</p>
| |
− | <ul>
| |
− | <li><p>If ''host'' is a string, the TCP server is bound to a single network
| |
− | interface specified by ''host''.</p></li>
| |
− | <li><p>If ''host'' is a sequence of strings, the TCP server is bound to all
| |
− | network interfaces specified by the sequence.</p></li>
| |
− | <li><p>If ''host'' is an empty string or <code>None</code>, all interfaces are
| |
− | assumed and a list of multiple sockets will be returned (most likely
| |
− | one for IPv4 and another one for IPv6).</p></li></ul>
| |
− | </li>
| |
− | <li><p>''family'' can be set to either [[../socket#socket|<code>socket.AF_INET</code>]] or
| |
− | [[../socket#socket|<code>AF_INET6</code>]] to force the socket to use IPv4 or IPv6.
| |
− | If not set, the ''family'' will be determined from host name
| |
− | (defaults to <code>AF_UNSPEC</code>).</p></li>
| |
− | <li><p>''flags'' is a bitmask for [[#asyncio.loop.getaddrinfo|<code>getaddrinfo()</code>]].</p></li>
| |
− | <li><p>''sock'' can optionally be specified in order to use a preexisting
| |
− | socket object. If specified, ''host'' and ''port'' must not be specified.</p></li>
| |
− | <li><p>''backlog'' is the maximum number of queued connections passed to
| |
− | [[../socket#socket.socket|<code>listen()</code>]] (defaults to 100).</p></li>
| |
− | <li><p>''ssl'' can be set to an [[../ssl#ssl|<code>SSLContext</code>]] instance to enable
| |
− | TLS over the accepted connections.</p></li>
| |
− | <li><p>''reuse_address'' tells the kernel to reuse a local socket in
| |
− | <code>TIME_WAIT</code> state, without waiting for its natural timeout to
| |
− | expire. If not specified will automatically be set to <code>True</code> on
| |
− | Unix.</p></li>
| |
− | <li><p>''reuse_port'' tells the kernel to allow this endpoint to be bound to the
| |
− | same port as other existing endpoints are bound to, so long as they all
| |
− | set this flag when being created. This option is not supported on
| |
− | Windows.</p></li>
| |
− | <li><p>''ssl_handshake_timeout'' is (for a TLS server) the time in seconds to wait
| |
− | for the TLS handshake to complete before aborting the connection.
| |
− | <code>60.0</code> seconds if <code>None</code> (default).</p></li>
| |
− | <li><p>''start_serving'' set to <code>True</code> (the default) causes the created server
| |
− | to start accepting connections immediately. When set to <code>False</code>,
| |
− | the user should await on [[#asyncio.Server.start_serving|<code>Server.start_serving()</code>]] or
| |
− | [[#asyncio.Server.serve_forever|<code>Server.serve_forever()</code>]] to make the server to start accepting
| |
− | connections.</p></li></ul>
| |
− | | |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能: </span>Added ''ssl_handshake_timeout'' and ''start_serving'' parameters.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.6 版更改: </span>The socket option <code>TCP_NODELAY</code> is set by default
| |
− | for all TCP connections.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.5 版更改: </span>Added support for SSL/TLS in [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]].</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.5.1 版更改: </span>The ''host'' parameter can be a sequence of strings.</p>
| |
− | | |
− | </div>
| |
− | <div class="admonition seealso">
| |
− | | |
− | <p>参见</p>
| |
− | <p>The [[../asyncio-stream#asyncio|<code>start_server()</code>]] function is a higher-level alternative API
| |
− | that returns a pair of [[../asyncio-stream#asyncio|<code>StreamReader</code>]] and [[../asyncio-stream#asyncio|<code>StreamWriter</code>]]
| |
− | that can be used in an async/await code.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>create_unix_server</code><span class="sig-paren">(</span>''protocol_factory'', ''path=None'', ''\*'', ''sock=None'', ''backlog=100'', ''ssl=None'', ''ssl_handshake_timeout=None'', ''start_serving=True''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Similar to [[#asyncio.loop.create_server|<code>loop.create_server()</code>]] but works with the
| |
− | [[../socket#socket|<code>AF_UNIX</code>]] socket family.</p>
| |
− | <p>''path'' is the name of a Unix domain socket, and is required,
| |
− | unless a ''sock'' argument is provided. Abstract Unix sockets,
| |
− | [[../stdtypes#str|<code>str</code>]], [[../stdtypes#bytes|<code>bytes</code>]], and [[../pathlib#pathlib|<code>Path</code>]] paths
| |
− | are supported.</p>
| |
− | <p>See the documentation of the [[#asyncio.loop.create_server|<code>loop.create_server()</code>]] method
| |
− | for information about arguments to this method.</p>
| |
− | <p>[[../intro#availability|<span class="std std-ref">Availability</span>]]: Unix.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能: </span>The ''ssl_handshake_timeout'' and ''start_serving'' parameters.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>The ''path'' parameter can now be a [[../pathlib#pathlib|<code>Path</code>]] object.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>connect_accepted_socket</code><span class="sig-paren">(</span>''protocol_factory'', ''sock'', ''\*'', ''ssl=None'', ''ssl_handshake_timeout=None''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Wrap an already accepted connection into a transport/protocol pair.</p>
| |
− | <p>This method can be used by servers that accept connections outside
| |
− | of asyncio but that use asyncio to handle them.</p>
| |
− | <p>Parameters:</p>
| |
− | <ul>
| |
− | <li><p>''protocol_factory'' must be a callable returning a
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">protocol</span>]] implementation.</p></li>
| |
− | <li><p>''sock'' is a preexisting socket object returned from
| |
− | [[../socket#socket.socket|<code>socket.accept</code>]].</p></li>
| |
− | <li><p>''ssl'' can be set to an [[../ssl#ssl|<code>SSLContext</code>]] to enable SSL over
| |
− | the accepted connections.</p></li>
| |
− | <li><p>''ssl_handshake_timeout'' is (for an SSL connection) the time in seconds to
| |
− | wait for the SSL handshake to complete before aborting the connection.
| |
− | <code>60.0</code> seconds if <code>None</code> (default).</p></li></ul>
| |
− | | |
− | <p>Returns a <code>(transport, protocol)</code> pair.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能: </span>The ''ssl_handshake_timeout'' parameter.</p>
| |
− | | |
− | </div>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.5.3 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
| | | |
| | | |
第726行: |
第280行: |
| <div id="transferring-files" class="section"> | | <div id="transferring-files" class="section"> |
| | | |
− | === [[#id8|Transferring files]] === | + | === 传输文件 === |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sendfile</code><span class="sig-paren">(</span>''<span class="n">transport</span>'', ''<span class="n">file</span>'', ''<span class="n">offset</span><span class="o">=</span><span class="default_value">0</span>'', ''<span class="n">count</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">*</span>'', ''<span class="n">fallback</span><span class="o">=</span><span class="default_value">True</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Send a ''file'' over a ''transport''. Return the total number of bytes
| |
− | sent.</p>
| |
− | <p>The method uses high-performance [[../os#os|<code>os.sendfile()</code>]] if available.</p>
| |
− | <p>''file'' must be a regular file object opened in binary mode.</p>
| |
− | <p>''offset'' tells from where to start reading the file. If specified,
| |
− | ''count'' is the total number of bytes to transmit as opposed to
| |
− | sending the file until EOF is reached. File position is always updated,
| |
− | even when this method raises an error, and
| |
− | [[../io#io.IOBase|<code>file.tell()</code>]] can be used to obtain the actual
| |
− | number of bytes sent.</p>
| |
− | <p>''fallback'' set to <code>True</code> makes asyncio to manually read and send
| |
− | the file when the platform does not support the sendfile system call
| |
− | (e.g. Windows or SSL socket on Unix).</p>
| |
− | <p>Raise [[../asyncio-exceptions#asyncio|<code>SendfileNotAvailableError</code>]] if the system does not support
| |
− | the ''sendfile'' syscall and ''fallback'' is <code>False</code>.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
| | | |
| | | |
第755行: |
第286行: |
| <div id="tls-upgrade" class="section"> | | <div id="tls-upgrade" class="section"> |
| | | |
− | === [[#id9|TLS Upgrade]] === | + | === TLS 升级 === |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>start_tls</code><span class="sig-paren">(</span>''transport'', ''protocol'', ''sslcontext'', ''\*'', ''server_side=False'', ''server_hostname=None'', ''ssl_handshake_timeout=None''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Upgrade an existing transport-based connection to TLS.</p>
| |
− | <p>Return a new transport instance, that the ''protocol'' must start using
| |
− | immediately after the ''await''. The ''transport'' instance passed to
| |
− | the ''start_tls'' method should never be used again.</p>
| |
− | <p>Parameters:</p>
| |
− | <ul>
| |
− | <li><p>''transport'' and ''protocol'' instances that methods like
| |
− | [[#asyncio.loop.create_server|<code>create_server()</code>]] and
| |
− | [[#asyncio.loop.create_connection|<code>create_connection()</code>]] return.</p></li>
| |
− | <li><p>''sslcontext'': a configured instance of [[../ssl#ssl|<code>SSLContext</code>]].</p></li>
| |
− | <li><p>''server_side'' pass <code>True</code> when a server-side connection is being
| |
− | upgraded (like the one created by [[#asyncio.loop.create_server|<code>create_server()</code>]]).</p></li>
| |
− | <li><p>''server_hostname'': sets or overrides the host name that the target
| |
− | server's certificate will be matched against.</p></li>
| |
− | <li><p>''ssl_handshake_timeout'' is (for a TLS connection) the time in seconds to
| |
− | wait for the TLS handshake to complete before aborting the connection.
| |
− | <code>60.0</code> seconds if <code>None</code> (default).</p></li></ul>
| |
− | | |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
| | | |
| | | |
第787行: |
第292行: |
| <div id="watching-file-descriptors" class="section"> | | <div id="watching-file-descriptors" class="section"> |
| | | |
− | === [[#id10|Watching file descriptors]] === | + | === 查看文件描述符 === |
| | | |
− | ; <code>loop.</code><code>add_reader</code><span class="sig-paren">(</span>''fd'', ''callback'', ''\*args''<span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">add_reader</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fd</span></span>'', ''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>''<span class="sig-paren">)</span> |
− | : Start monitoring the ''fd'' file descriptor for read availability and invoke ''callback'' with the specified arguments once ''fd'' is available for reading. | + | : 开始监视 ''fd'' 文件描述符的读取可用性,并在 ''fd'' 可供读取时使用指定的参数调用 ''callback''。 |
| | | |
− | ; <code>loop.</code><code>remove_reader</code><span class="sig-paren">(</span>''<span class="n">fd</span>''<span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">remove_reader</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fd</span></span>''<span class="sig-paren">)</span> |
− | : Stop monitoring the ''fd'' file descriptor for read availability. | + | : 停止监视 ''fd'' 文件描述符以获取读取可用性。 |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>add_writer</code><span class="sig-paren">(</span>''fd'', ''callback'', ''\*args''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">add_writer</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fd</span></span>'', ''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Start monitoring the ''fd'' file descriptor for write availability and | + | <dd><p>开始监视 ''fd'' 文件描述符的写入可用性,并在 ''fd'' 可用于写入时使用指定的参数调用 ''callback''。</p> |
− | invoke ''callback'' with the specified arguments once ''fd'' is available for
| + | <p>使用 [[../functools#functools|functools.partial()]] [[#asyncio-pass-keywords|将关键字参数]] 传递给 ''callback''。</p></dd></dl> |
− | writing.</p>
| |
− | <p>Use [[../functools#functools|<code>functools.partial()</code>]] [[#asyncio-pass-keywords|<span class="std std-ref">to pass keyword arguments</span>]] to ''callback''.</p></dd></dl> | |
| | | |
− | ; <code>loop.</code><code>remove_writer</code><span class="sig-paren">(</span>''<span class="n">fd</span>''<span class="sig-paren">)</span> | + | ; <span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">remove_writer</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">fd</span></span>''<span class="sig-paren">)</span> |
− | : Stop monitoring the ''fd'' file descriptor for write availability. | + | : 停止监视 ''fd'' 文件描述符以获取写入可用性。 |
| | | |
− | See also [[../asyncio-platforms#asyncio-platform-support|<span class="std std-ref">Platform Support</span>]] section
| + | 有关这些方法的一些限制,另请参阅 [[../asyncio-platforms#asyncio-platform-support|平台支持]] 部分。 |
− | for some limitations of these methods.
| |
| | | |
| | | |
第812行: |
第314行: |
| <div id="working-with-socket-objects-directly" class="section"> | | <div id="working-with-socket-objects-directly" class="section"> |
| | | |
− | === [[#id11|Working with socket objects directly]] === | + | === 直接使用套接字对象 === |
− | | |
− | In general, protocol implementations that use transport-based APIs
| |
− | such as [[#asyncio.loop.create_connection|<code>loop.create_connection()</code>]] and [[#asyncio.loop.create_server|<code>loop.create_server()</code>]]
| |
− | are faster than implementations that work with sockets directly.
| |
− | However, there are some use cases when performance is not critical, and
| |
− | working with [[../socket#socket|<code>socket</code>]] objects directly is more
| |
− | convenient.
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_recv</code><span class="sig-paren">(</span>''<span class="n">sock</span>'', ''<span class="n">nbytes</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Receive up to ''nbytes'' from ''sock''. Asynchronous version of
| |
− | [[../socket#socket.socket|<code>socket.recv()</code>]].</p>
| |
− | <p>Return the received data as a bytes object.</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>Even though this method was always documented as a coroutine
| |
− | method, releases before Python 3.7 returned a [[../asyncio-future#asyncio|<code>Future</code>]].
| |
− | Since Python 3.7 this is an <code>async def</code> method.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_recv_into</code><span class="sig-paren">(</span>''<span class="n">sock</span>'', ''<span class="n">buf</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Receive data from ''sock'' into the ''buf'' buffer. Modeled after the blocking
| |
− | [[../socket#socket.socket|<code>socket.recv_into()</code>]] method.</p>
| |
− | <p>Return the number of bytes written to the buffer.</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_sendall</code><span class="sig-paren">(</span>''<span class="n">sock</span>'', ''<span class="n">data</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Send ''data'' to the ''sock'' socket. Asynchronous version of
| |
− | [[../socket#socket.socket|<code>socket.sendall()</code>]].</p>
| |
− | <p>This method continues to send to the socket until either all data
| |
− | in ''data'' has been sent or an error occurs. <code>None</code> is returned
| |
− | on success. On error, an exception is raised. Additionally, there is no way
| |
− | to determine how much data, if any, was successfully processed by the
| |
− | receiving end of the connection.</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>Even though the method was always documented as a coroutine
| |
− | method, before Python 3.7 it returned an [[../asyncio-future#asyncio|<code>Future</code>]].
| |
− | Since Python 3.7, this is an <code>async def</code> method.</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_connect</code><span class="sig-paren">(</span>''<span class="n">sock</span>'', ''<span class="n">address</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Connect ''sock'' to a remote socket at ''address''.</p>
| |
− | <p>Asynchronous version of [[../socket#socket.socket|<code>socket.connect()</code>]].</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.5.2 版更改: </span><code>address</code> no longer needs to be resolved. <code>sock_connect</code>
| |
− | will try to check if the ''address'' is already resolved by calling
| |
− | [[../socket#socket|<code>socket.inet_pton()</code>]]. If not,
| |
− | [[#asyncio.loop.getaddrinfo|<code>loop.getaddrinfo()</code>]] will be used to resolve the
| |
− | ''address''.</p>
| |
− | | |
− | </div>
| |
− | <div class="admonition seealso">
| |
− | | |
− | <p>参见</p>
| |
− | <p>[[#asyncio.loop.create_connection|<code>loop.create_connection()</code>]]
| |
− | and [[../asyncio-stream#asyncio|<code>asyncio.open_connection()</code>]].</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_accept</code><span class="sig-paren">(</span>''<span class="n">sock</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Accept a connection. Modeled after the blocking
| |
− | [[../socket#socket.socket|<code>socket.accept()</code>]] method.</p>
| |
− | <p>The socket must be bound to an address and listening
| |
− | for connections. The return value is a pair <code>(conn, address)</code> where ''conn''
| |
− | is a ''new'' socket object usable to send and receive data on the connection,
| |
− | and ''address'' is the address bound to the socket on the other end of the
| |
− | connection.</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>Even though the method was always documented as a coroutine
| |
− | method, before Python 3.7 it returned a [[../asyncio-future#asyncio|<code>Future</code>]].
| |
− | Since Python 3.7, this is an <code>async def</code> method.</p>
| |
− | | |
− | </div>
| |
− | <div class="admonition seealso">
| |
− | | |
− | <p>参见</p>
| |
− | <p>[[#asyncio.loop.create_server|<code>loop.create_server()</code>]] and [[../asyncio-stream#asyncio|<code>start_server()</code>]].</p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>sock_sendfile</code><span class="sig-paren">(</span>''sock'', ''file'', ''offset=0'', ''count=None'', ''\*'', ''fallback=True''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Send a file using high-performance [[../os#os|<code>os.sendfile</code>]] if possible.
| |
− | Return the total number of bytes sent.</p>
| |
− | <p>Asynchronous version of [[../socket#socket.socket|<code>socket.sendfile()</code>]].</p>
| |
− | <p>''sock'' must be a non-blocking [[../socket#socket|<code>socket.SOCK_STREAM</code>]]
| |
− | [[../socket#socket|<code>socket</code>]].</p>
| |
− | <p>''file'' must be a regular file object open in binary mode.</p>
| |
− | <p>''offset'' tells from where to start reading the file. If specified,
| |
− | ''count'' is the total number of bytes to transmit as opposed to
| |
− | sending the file until EOF is reached. File position is always updated,
| |
− | even when this method raises an error, and
| |
− | [[../io#io.IOBase|<code>file.tell()</code>]] can be used to obtain the actual
| |
− | number of bytes sent.</p>
| |
− | <p>''fallback'', when set to <code>True</code>, makes asyncio manually read and send
| |
− | the file when the platform does not support the sendfile syscall
| |
− | (e.g. Windows or SSL socket on Unix).</p>
| |
− | <p>Raise [[../asyncio-exceptions#asyncio|<code>SendfileNotAvailableError</code>]] if the system does not support
| |
− | ''sendfile'' syscall and ''fallback'' is <code>False</code>.</p>
| |
− | <p>''sock'' must be a non-blocking socket.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p>
| |
| | | |
− | </div></dd></dl> | + | 通常,使用基于传输的 API(例如 <code>loop.create_connection()</code> 和 <code>loop.create_server()</code>)的协议实现比直接使用套接字的实现要快。 但是,在某些情况下,性能并不重要,直接使用 [[../socket#socket|socket]] 对象更方便。 |
| | | |
| | | |
第941行: |
第322行: |
| <div id="dns" class="section"> | | <div id="dns" class="section"> |
| | | |
− | === [[#id12|DNS]] === | + | === 域名系统 === |
− | | |
− | ; ''coroutine'' <code>loop.</code><code>getaddrinfo</code><span class="sig-paren">(</span>''host'', ''port'', ''\*'', ''family=0'', ''type=0'', ''proto=0'', ''flags=0''<span class="sig-paren">)</span>
| |
− | : Asynchronous version of [[../socket#socket|<code>socket.getaddrinfo()</code>]].
| |
− | | |
− | ; ''coroutine'' <code>loop.</code><code>getnameinfo</code><span class="sig-paren">(</span>''<span class="n">sockaddr</span>'', ''<span class="n">flags</span><span class="o">=</span><span class="default_value">0</span>''<span class="sig-paren">)</span>
| |
− | : Asynchronous version of [[../socket#socket|<code>socket.getnameinfo()</code>]].
| |
| | | |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <span class="versionmodified changed">在 3.7 版更改: </span>Both ''getaddrinfo'' and ''getnameinfo'' methods were always documented | + | <span class="versionmodified changed"> 3.7 版更改: </span> ''getaddrinfo'' 和 ''getnameinfo'' 方法总是被记录为返回协程,但在 Python 3.7 之前,它们实际上返回 [[asyncio-future.html#asyncio.Future|]asyncio.Future]] 对象。 从 Python 3.7 开始,这两种方法都是协程。 |
− | to return a coroutine, but prior to Python 3.7 they were, in fact,
| |
− | returning [[../asyncio-future#asyncio|<code>asyncio.Future</code>]] objects. Starting with Python 3.7
| |
− | both methods are coroutines.
| |
| | | |
| | | |
第962行: |
第334行: |
| <div id="working-with-pipes" class="section"> | | <div id="working-with-pipes" class="section"> |
| | | |
− | === [[#id13|Working with pipes]] === | + | === 使用管道 === |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>connect_read_pipe</code><span class="sig-paren">(</span>''<span class="n">protocol_factory</span>'', ''<span class="n">pipe</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Register the read end of ''pipe'' in the event loop.</p>
| |
− | <p>''protocol_factory'' must be a callable returning an
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">asyncio protocol</span>]] implementation.</p>
| |
− | <p>''pipe'' is a [[../../glossary#term-file-object|<span class="xref std std-term">file-like object</span>]].</p>
| |
− | <p>Return pair <code>(transport, protocol)</code>, where ''transport'' supports
| |
− | the [[../asyncio-protocol#asyncio|<code>ReadTransport</code>]] interface and ''protocol'' is an object
| |
− | instantiated by the ''protocol_factory''.</p>
| |
− | <p>With [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]] event loop, the ''pipe'' is set to
| |
− | non-blocking mode.</p></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>connect_write_pipe</code><span class="sig-paren">(</span>''<span class="n">protocol_factory</span>'', ''<span class="n">pipe</span>''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Register the write end of ''pipe'' in the event loop.</p>
| |
− | <p>''protocol_factory'' must be a callable returning an
| |
− | [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">asyncio protocol</span>]] implementation.</p>
| |
− | <p>''pipe'' is [[../../glossary#term-file-object|<span class="xref std std-term">file-like object</span>]].</p>
| |
− | <p>Return pair <code>(transport, protocol)</code>, where ''transport'' supports
| |
− | [[../asyncio-protocol#asyncio|<code>WriteTransport</code>]] interface and ''protocol'' is an object
| |
− | instantiated by the ''protocol_factory''.</p>
| |
− | <p>With [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]] event loop, the ''pipe'' is set to
| |
− | non-blocking mode.</p></dd></dl>
| |
| | | |
| <div class="admonition note"> | | <div class="admonition note"> |
| | | |
− | 注解
| + | 笔记 |
| | | |
− | [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]] does not support the above methods on | + | [[#asyncio.SelectorEventLoop|SelectorEventLoop]] 在 Windows 上不支持上述方法。 使用 [[#asyncio.ProactorEventLoop|ProactorEventLoop]] 代替 Windows。 |
− | Windows. Use [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]] instead for Windows. | |
| | | |
| | | |
第999行: |
第346行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | The [[#asyncio.loop.subprocess_exec|<code>loop.subprocess_exec()</code>]] and
| + | <code>loop.subprocess_exec()</code> 和 <code>loop.subprocess_shell()</code> 方法。 |
− | [[#asyncio.loop.subprocess_shell|<code>loop.subprocess_shell()</code>]] methods.
| |
| | | |
| | | |
第1,010行: |
第356行: |
| <div id="unix-signals" class="section"> | | <div id="unix-signals" class="section"> |
| | | |
− | === [[#id14|Unix signals]] === | + | === Unix 信号 === |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>add_signal_handler</code><span class="sig-paren">(</span>''signum'', ''callback'', ''\*args''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">add_signal_handler</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">signum</span></span>'', ''<span class="n"><span class="pre">callback</span></span>'', ''<span class="o"><span class="pre">*</span></span><span class="n"><span class="pre">args</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Set ''callback'' as the handler for the ''signum'' signal.</p> | + | <dd><p>将 ''callback'' 设置为 ''signum'' 信号的处理程序。</p> |
− | <p>The callback will be invoked by ''loop'', along with other queued callbacks | + | <p>回调将由 ''loop'' 以及该事件循环的其他排队回调和可运行协程调用。 与使用 [[../signal#signal|signal.signal()]] 注册的信号处理程序不同,使用此函数注册的回调允许与事件循环交互。</p> |
− | and runnable coroutines of that event loop. Unlike signal handlers
| + | <p>如果信号编号无效或无法捕获,则引发 [[../exceptions#ValueError|ValueError]]。 如果设置处理程序出现问题,则引发 [[../exceptions#RuntimeError|RuntimeError]]。</p> |
− | registered using [[../signal#signal|<code>signal.signal()</code>]], a callback registered with this
| + | <p>使用 [[../functools#functools|functools.partial()]] [[#asyncio-pass-keywords|将关键字参数]] 传递给 ''callback''。</p> |
− | function is allowed to interact with the event loop.</p>
| + | <p>和[[../signal#signal|signal.signal()]]一样,这个函数必须在主线程中调用。</p></dd></dl> |
− | <p>Raise [[../exceptions#ValueError|<code>ValueError</code>]] if the signal number is invalid or uncatchable. | |
− | Raise [[../exceptions#RuntimeError|<code>RuntimeError</code>]] if there is a problem setting up the handler.</p>
| |
− | <p>Use [[../functools#functools|<code>functools.partial()</code>]] [[#asyncio-pass-keywords|<span class="std std-ref">to pass keyword arguments</span>]] to ''callback''.</p> | |
− | <p>Like [[../signal#signal|<code>signal.signal()</code>]], this function must be invoked in the main | |
− | thread.</p></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>remove_signal_handler</code><span class="sig-paren">(</span>''<span class="n">sig</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">remove_signal_handler</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">sig</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Remove the handler for the ''sig'' signal.</p> | + | <dd><p>删除 ''sig'' 信号的处理程序。</p> |
− | <p>Return <code>True</code> if the signal handler was removed, or <code>False</code> if | + | <p>如果删除了信号处理程序,则返回 <code>True</code>,如果没有为给定信号设置处理程序,则返回 <code>False</code>。</p></dd></dl> |
− | no handler was set for the given signal.</p>
| |
− | <p>[[../intro#availability|<span class="std std-ref">Availability</span>]]: Unix.</p></dd></dl>
| |
| | | |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | The [[../signal#module-signal|<code>signal</code>]] module.
| + | [[../signal#module-signal|信号]]模块。 |
| | | |
| | | |
第1,044行: |
第383行: |
| <div id="executing-code-in-thread-or-process-pools" class="section"> | | <div id="executing-code-in-thread-or-process-pools" class="section"> |
| | | |
− | === [[#id15|Executing code in thread or process pools]] === | + | === 在线程或进程池中执行代码 === |
− | | |
− | <dl>
| |
− | <dt>''awaitable'' <code>loop.</code><code>run_in_executor</code><span class="sig-paren">(</span>''executor'', ''func'', ''\*args''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Arrange for ''func'' to be called in the specified executor.</p>
| |
− | <p>The ''executor'' argument should be an [[../concurrent.futures#concurrent.futures|<code>concurrent.futures.Executor</code>]]
| |
− | instance. The default executor is used if ''executor'' is <code>None</code>.</p>
| |
− | <p>Example:</p>
| |
− | <div class="highlight-python3 notranslate">
| |
− | | |
− | <div class="highlight">
| |
− | | |
− | <pre>import asyncio
| |
− | import concurrent.futures
| |
− | | |
− | def blocking_io():
| |
− | # File operations (such as logging) can block the
| |
− | # event loop: run them in a thread pool.
| |
− | with open('/dev/urandom', 'rb') as f:
| |
− | return f.read(100)
| |
− | | |
− | def cpu_bound():
| |
− | # CPU-bound operations will block the event loop:
| |
− | # in general it is preferable to run them in a
| |
− | # process pool.
| |
− | return sum(i * i for i in range(10 ** 7))
| |
− | | |
− | async def main():
| |
− | loop = asyncio.get_running_loop()
| |
− | | |
− | ## Options:
| |
− | | |
− | # 1. Run in the default loop's executor:
| |
− | result = await loop.run_in_executor(
| |
− | None, blocking_io)
| |
− | print('default thread pool', result)
| |
− | | |
− | # 2. Run in a custom thread pool:
| |
− | with concurrent.futures.ThreadPoolExecutor() as pool:
| |
− | result = await loop.run_in_executor(
| |
− | pool, blocking_io)
| |
− | print('custom thread pool', result)
| |
− | | |
− | # 3. Run in a custom process pool:
| |
− | with concurrent.futures.ProcessPoolExecutor() as pool:
| |
− | result = await loop.run_in_executor(
| |
− | pool, cpu_bound)
| |
− | print('custom process pool', result)
| |
− | | |
− | asyncio.run(main())</pre>
| |
− | | |
− | </div>
| |
− | | |
− | </div>
| |
− | <p>This method returns a [[../asyncio-future#asyncio|<code>asyncio.Future</code>]] object.</p>
| |
− | <p>Use [[../functools#functools|<code>functools.partial()</code>]] [[#asyncio-pass-keywords|<span class="std std-ref">to pass keyword arguments</span>]] to ''func''.</p>
| |
− | <div class="versionchanged">
| |
− | | |
− | <p><span class="versionmodified changed">在 3.5.3 版更改: </span>[[#asyncio.loop.run_in_executor|<code>loop.run_in_executor()</code>]] no longer configures the
| |
− | <code>max_workers</code> of the thread pool executor it creates, instead
| |
− | leaving it up to the thread pool executor
| |
− | ([[../concurrent.futures#concurrent.futures|<code>ThreadPoolExecutor</code>]]) to set the
| |
− | default.</p>
| |
− | | |
− | </div></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>set_default_executor</code><span class="sig-paren">(</span>''<span class="n">executor</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">set_default_executor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">executor</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Set ''executor'' as the default executor used by [[#asyncio.loop.run_in_executor|<code>run_in_executor()</code>]]. | + | <dd><p>将 ''executor'' 设置为 <code>run_in_executor()</code> 使用的默认执行器。 ''executor'' 应该是 [[../concurrent.futures#concurrent.futures|ThreadPoolExecutor]] 的一个实例。</p> |
− | ''executor'' should be an instance of | |
− | [[../concurrent.futures#concurrent.futures|<code>ThreadPoolExecutor</code>]].</p> | |
| <div class="deprecated"> | | <div class="deprecated"> |
| | | |
− | <p><span class="versionmodified deprecated">3.8 版后已移除: </span>Using an executor that is not an instance of | + | <p><span class="versionmodified deprecated"> 自 3.8 版起已弃用:</span> 不推荐使用不是 [[../concurrent.futures#concurrent.futures|ThreadPoolExecutor]] 实例的执行程序,并将在 Python 3.9 中触发错误。</p> |
− | [[../concurrent.futures#concurrent.futures|<code>ThreadPoolExecutor</code>]] is deprecated and | |
− | will trigger an error in Python 3.9.</p>
| |
| | | |
| </div> | | </div> |
− | <p>''executor'' must be an instance of | + | <p>''executor'' 必须是 [[../concurrent.futures#concurrent.futures|concurrent.futures.ThreadPoolExecutor]] 的实例。</p></dd></dl> |
− | [[../concurrent.futures#concurrent.futures|<code>concurrent.futures.ThreadPoolExecutor</code>]].</p></dd></dl> | |
| | | |
| | | |
第1,129行: |
第399行: |
| <div id="error-handling-api" class="section"> | | <div id="error-handling-api" class="section"> |
| | | |
− | === [[#id16|Error Handling API]] === | + | === 错误处理 API === |
| | | |
− | Allows customizing how exceptions are handled in the event loop.
| + | 允许自定义如何在事件循环中处理异常。 |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>set_exception_handler</code><span class="sig-paren">(</span>''<span class="n">handler</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">set_exception_handler</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">handler</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Set ''handler'' as the new event loop exception handler.</p> | + | <dd><p>将 ''handler'' 设置为新的事件循环异常处理程序。</p> |
− | <p>If ''handler'' is <code>None</code>, the default exception handler will | + | <p>如果 ''handler'' 是 <code>None</code>,将设置默认异常处理程序。 否则,''handler'' 必须是一个签名匹配 <code>(loop, context)</code> 的可调用对象,其中 <code>loop</code> 是对活动事件循环的引用,而 <code>context</code> 是一个 [ X162X] 包含异常详细信息的对象(有关上下文的详细信息,请参阅 [[#asyncio.loop.call_exception_handler|call_exception_handler()]] 文档)。</p></dd></dl> |
− | be set. Otherwise, ''handler'' must be a callable with the signature
| |
− | matching <code>(loop, context)</code>, where <code>loop</code>
| |
− | is a reference to the active event loop, and <code>context</code>
| |
− | is a <code>dict</code> object containing the details of the exception
| |
− | (see [[#asyncio.loop.call_exception_handler|<code>call_exception_handler()</code>]] documentation for details
| |
− | about context).</p></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>get_exception_handler</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">get_exception_handler</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Return the current exception handler, or <code>None</code> if no custom | + | <dd><p>返回当前异常处理程序,如果没有设置自定义异常处理程序,则返回 <code>None</code>。</p> |
− | exception handler was set.</p>
| |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.5.2 新版功能.</span></p> | + | <p><span class="versionmodified added">版本 3.5.2 中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>default_exception_handler</code><span class="sig-paren">(</span>''<span class="n">context</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">default_exception_handler</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Default exception handler.</p> | + | <dd><p>默认异常处理程序。</p> |
− | <p>This is called when an exception occurs and no exception | + | <p>当发生异常且未设置异常处理程序时调用此方法。 这可以由想要遵循默认处理程序行为的自定义异常处理程序调用。</p> |
− | handler is set. This can be called by a custom exception
| + | <p>''context'' 参数的含义与 [[#asyncio.loop.call_exception_handler|call_exception_handler()]] 中的含义相同。</p></dd></dl> |
− | handler that wants to defer to the default handler behavior.</p>
| |
− | <p>''context'' parameter has the same meaning as in | |
− | [[#asyncio.loop.call_exception_handler|<code>call_exception_handler()</code>]].</p></dd></dl> | |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>call_exception_handler</code><span class="sig-paren">(</span>''<span class="n">context</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">call_exception_handler</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">context</span></span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Call the current event loop exception handler.</p> | + | <dd><p>调用当前事件循环异常处理程序。</p> |
− | <p>''context'' is a <code>dict</code> object containing the following keys | + | <p>''context'' 是一个 <code>dict</code> 对象,包含以下键(新的键可能会在未来的 Python 版本中引入):</p> |
− | (new keys may be introduced in future Python versions):</p>
| |
| <ul> | | <ul> |
− | <li><p>'message': Error message;</p></li> | + | <li><p>'message':错误信息;</p></li> |
− | <li><p>'exception' (optional): Exception object;</p></li> | + | <li><p>“异常”(可选):异常对象;</p></li> |
− | <li><p>'future' (optional): [[../asyncio-future#asyncio|<code>asyncio.Future</code>]] instance;</p></li> | + | <li><p>'future'(可选):[[../asyncio-future#asyncio|asyncio.Future]] 实例;</p></li> |
− | <li><p>'handle' (optional): [[#asyncio.Handle|<code>asyncio.Handle</code>]] instance;</p></li> | + | <li><p>'handle'(可选):[[#asyncio.Handle|asyncio.Handle]] 实例;</p></li> |
− | <li><p>'protocol' (optional): [[../asyncio-protocol#asyncio-protocol|<span class="std std-ref">Protocol</span>]] instance;</p></li> | + | <li><p>'protocol'(可选):[[../asyncio-protocol#asyncio-protocol|Protocol]] 实例;</p></li> |
− | <li><p>'transport' (optional): [[../asyncio-protocol#asyncio-transport|<span class="std std-ref">Transport</span>]] instance;</p></li> | + | <li><p>'transport'(可选):[[../asyncio-protocol#asyncio-transport|Transport]] 实例;</p></li> |
− | <li><p>'socket' (optional): [[../socket#socket|<code>socket.socket</code>]] instance.</p></li></ul> | + | <li><p>'socket'(可选):[[../socket#socket|socket.socket]] 实例。</p></li></ul> |
| | | |
| <div class="admonition note"> | | <div class="admonition note"> |
| | | |
− | <p>注解</p> | + | <p>笔记</p> |
− | <p>This method should not be overloaded in subclassed | + | <p>此方法不应在子类事件循环中重载。 对于自定义异常处理,请使用 [[#asyncio.loop.set_exception_handler|set_exception_handler()]] 方法。</p> |
− | event loops. For custom exception handling, use
| |
− | the [[#asyncio.loop.set_exception_handler|<code>set_exception_handler()</code>]] method.</p>
| |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
第1,190行: |
第447行: |
| <div id="enabling-debug-mode" class="section"> | | <div id="enabling-debug-mode" class="section"> |
| | | |
− | === [[#id17|Enabling debug mode]] === | + | === 启用调试模式 === |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>get_debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">get_debug</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Get the debug mode ([[../functions#bool|<code>bool</code>]]) of the event loop.</p> | + | <dd><p>获取事件循环的调试模式([[../functions#bool|bool]])。</p> |
− | <p>The default value is <code>True</code> if the environment variable | + | <p>如果环境变量 <span id="index-3" class="target"></span>[[../../using/cmdline#envvar-PYTHONASYNCIODEBUG|PYTHONASYNCIODEBUG]] 设置为非空字符串,则默认值为 <code>True</code>,否则为 <code>False</code>。</p></dd></dl> |
− | <span id="index-5" class="target"></span>[[../../using/cmdline#envvar-PYTHONASYNCIODEBUG|<code>PYTHONASYNCIODEBUG</code>]] is set to a non-empty string, <code>False</code> | |
− | otherwise.</p></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>loop.</code><code>set_debug</code><span class="sig-paren">(</span>''<span class="n">enabled</span><span class="p">:</span> <span class="n">[[../functions#bool|bool]]</span>''<span class="sig-paren">)</span></dt> | + | <dt><span class="sig-prename descclassname"><span class="pre">loop.</span></span><span class="sig-name descname"><span class="pre">set_debug</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">enabled</span></span><span class="p"><span class="pre">:</span></span> <span class="n">[[../functions#bool|<span class="pre">bool</span>]]</span>''<span class="sig-paren">)</span></dt> |
− | <dd><p>Set the debug mode of the event loop.</p> | + | <dd><p>设置事件循环的调试模式。</p> |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>The new [[../devmode#devmode|<span class="std std-ref">Python Development Mode</span>]] can now also be used | + | <p><span class="versionmodified changed"> 3.7 版更改: </span> 新的 [[../devmode#devmode|Python 开发模式]] 现在也可以用于启用调试模式。</p> |
− | to enable the debug mode.</p>
| |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
第1,211行: |
第465行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | The [[../asyncio-dev#asyncio-debug-mode|<span class="std std-ref">debug mode of asyncio</span>]].
| + | asyncio [[../asyncio-dev#asyncio-debug-mode|的]] 调试模式。 |
| | | |
| | | |
第1,221行: |
第475行: |
| <div id="running-subprocesses" class="section"> | | <div id="running-subprocesses" class="section"> |
| | | |
− | === [[#id18|Running Subprocesses]] === | + | === 运行子进程 === |
| | | |
− | Methods described in this subsections are low-level. In regular
| + | 本小节中描述的方法是低级的。 在常规 async/await 代码中,请考虑使用高级 <code>asyncio.create_subprocess_shell()</code> 和 <code>asyncio.create_subprocess_exec()</code> 便利函数。 |
− | async/await code consider using the high-level | |
− | [[../asyncio-subprocess#asyncio|<code>asyncio.create_subprocess_shell()</code>]] and
| |
− | [[../asyncio-subprocess#asyncio|<code>asyncio.create_subprocess_exec()</code>]] convenience functions instead.
| |
| | | |
| <div class="admonition note"> | | <div class="admonition note"> |
| | | |
− | 注解
| + | 笔记 |
| | | |
− | The default asyncio event loop on '''Windows''' does not support
| + | '''Windows''' 上的默认 asyncio 事件循环不支持子进程。 有关详细信息,请参阅 Windows 上的子进程支持 [X37X]。 |
− | subprocesses. See [[../asyncio-platforms#asyncio-windows-subprocess|<span class="std std-ref">Subprocess Support on Windows</span>]] for details.
| |
| | | |
| | | |
| </div> | | </div> |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>subprocess_exec</code><span class="sig-paren">(</span>''protocol_factory'', ''\*args'', ''stdin=subprocess.PIPE'', ''stdout=subprocess.PIPE'', ''stderr=subprocess.PIPE'', ''\*\*kwargs''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Create a subprocess from one or more string arguments specified by
| |
− | ''args''.</p>
| |
− | <p>''args'' must be a list of strings represented by:</p>
| |
− | <ul>
| |
− | <li><p>[[../stdtypes#str|<code>str</code>]];</p></li>
| |
− | <li><p>or [[../stdtypes#bytes|<code>bytes</code>]], encoded to the
| |
− | [[../os#filesystem-encoding|<span class="std std-ref">filesystem encoding</span>]].</p></li></ul>
| |
− |
| |
− | <p>The first string specifies the program executable,
| |
− | and the remaining strings specify the arguments. Together, string
| |
− | arguments form the <code>argv</code> of the program.</p>
| |
− | <p>This is similar to the standard library [[../subprocess#subprocess|<code>subprocess.Popen</code>]]
| |
− | class called with <code>shell=False</code> and the list of strings passed as
| |
− | the first argument; however, where [[../subprocess#subprocess|<code>Popen</code>]] takes
| |
− | a single argument which is list of strings, ''subprocess_exec''
| |
− | takes multiple string arguments.</p>
| |
− | <p>The ''protocol_factory'' must be a callable returning a subclass of the
| |
− | [[../asyncio-protocol#asyncio|<code>asyncio.SubprocessProtocol</code>]] class.</p>
| |
− | <p>Other parameters:</p>
| |
− | <ul>
| |
− | <li><p>''stdin'' can be any of these:</p>
| |
− | <ul>
| |
− | <li><p>a file-like object representing a pipe to be connected to the
| |
− | subprocess's standard input stream using
| |
− | [[#asyncio.loop.connect_write_pipe|<code>connect_write_pipe()</code>]]</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.PIPE</code>]] constant (default) which will create a new
| |
− | pipe and connect it,</p></li>
| |
− | <li><p>the value <code>None</code> which will make the subprocess inherit the file
| |
− | descriptor from this process</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.DEVNULL</code>]] constant which indicates that the
| |
− | special [[../os#os|<code>os.devnull</code>]] file will be used</p></li></ul>
| |
− | </li>
| |
− | <li><p>''stdout'' can be any of these:</p>
| |
− | <ul>
| |
− | <li><p>a file-like object representing a pipe to be connected to the
| |
− | subprocess's standard output stream using
| |
− | [[#asyncio.loop.connect_write_pipe|<code>connect_write_pipe()</code>]]</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.PIPE</code>]] constant (default) which will create a new
| |
− | pipe and connect it,</p></li>
| |
− | <li><p>the value <code>None</code> which will make the subprocess inherit the file
| |
− | descriptor from this process</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.DEVNULL</code>]] constant which indicates that the
| |
− | special [[../os#os|<code>os.devnull</code>]] file will be used</p></li></ul>
| |
− | </li>
| |
− | <li><p>''stderr'' can be any of these:</p>
| |
− | <ul>
| |
− | <li><p>a file-like object representing a pipe to be connected to the
| |
− | subprocess's standard error stream using
| |
− | [[#asyncio.loop.connect_write_pipe|<code>connect_write_pipe()</code>]]</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.PIPE</code>]] constant (default) which will create a new
| |
− | pipe and connect it,</p></li>
| |
− | <li><p>the value <code>None</code> which will make the subprocess inherit the file
| |
− | descriptor from this process</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.DEVNULL</code>]] constant which indicates that the
| |
− | special [[../os#os|<code>os.devnull</code>]] file will be used</p></li>
| |
− | <li><p>the [[../subprocess#subprocess|<code>subprocess.STDOUT</code>]] constant which will connect the standard
| |
− | error stream to the process' standard output stream</p></li></ul>
| |
− | </li>
| |
− | <li><p>All other keyword arguments are passed to [[../subprocess#subprocess|<code>subprocess.Popen</code>]]
| |
− | without interpretation, except for ''bufsize'', ''universal_newlines'',
| |
− | ''shell'', ''text'', ''encoding'' and ''errors'', which should not be specified
| |
− | at all.</p>
| |
− | <p>The <code>asyncio</code> subprocess API does not support decoding the streams
| |
− | as text. [[../stdtypes#bytes|<code>bytes.decode()</code>]] can be used to convert the bytes returned
| |
− | from the stream to text.</p></li></ul>
| |
− |
| |
− | <p>See the constructor of the [[../subprocess#subprocess|<code>subprocess.Popen</code>]] class
| |
− | for documentation on other arguments.</p>
| |
− | <p>Returns a pair of <code>(transport, protocol)</code>, where ''transport''
| |
− | conforms to the [[../asyncio-protocol#asyncio|<code>asyncio.SubprocessTransport</code>]] base class and
| |
− | ''protocol'' is an object instantiated by the ''protocol_factory''.</p></dd></dl>
| |
− |
| |
− | <dl>
| |
− | <dt>''coroutine'' <code>loop.</code><code>subprocess_shell</code><span class="sig-paren">(</span>''protocol_factory'', ''cmd'', ''\*'', ''stdin=subprocess.PIPE'', ''stdout=subprocess.PIPE'', ''stderr=subprocess.PIPE'', ''\*\*kwargs''<span class="sig-paren">)</span></dt>
| |
− | <dd><p>Create a subprocess from ''cmd'', which can be a [[../stdtypes#str|<code>str</code>]] or a
| |
− | [[../stdtypes#bytes|<code>bytes</code>]] string encoded to the
| |
− | [[../os#filesystem-encoding|<span class="std std-ref">filesystem encoding</span>]],
| |
− | using the platform's "shell" syntax.</p>
| |
− | <p>This is similar to the standard library [[../subprocess#subprocess|<code>subprocess.Popen</code>]]
| |
− | class called with <code>shell=True</code>.</p>
| |
− | <p>The ''protocol_factory'' must be a callable returning a subclass of the
| |
− | [[../asyncio-protocol#asyncio|<code>SubprocessProtocol</code>]] class.</p>
| |
− | <p>See [[#asyncio.loop.subprocess_exec|<code>subprocess_exec()</code>]] for more details about
| |
− | the remaining arguments.</p>
| |
− | <p>Returns a pair of <code>(transport, protocol)</code>, where ''transport''
| |
− | conforms to the [[../asyncio-protocol#asyncio|<code>SubprocessTransport</code>]] base class and
| |
− | ''protocol'' is an object instantiated by the ''protocol_factory''.</p></dd></dl>
| |
− |
| |
| <div class="admonition note"> | | <div class="admonition note"> |
| | | |
− | 注解
| + | 笔记 |
| | | |
− | It is the application's responsibility to ensure that all whitespace
| + | 应用程序有责任确保正确引用所有空格和特殊字符以避免 [https://en.wikipedia.org/wiki/Shell_injection#Shell_injection shell 注入] 漏洞。 [[../shlex#shlex|shlex.quote()]] 函数可用于正确转义将用于构造 shell 命令的字符串中的空格和特殊字符。 |
− | and special characters are quoted appropriately to avoid [https://en.wikipedia.org/wiki/Shell_injection#Shell_injection shell injection]
| |
− | vulnerabilities. The [[../shlex#shlex|<code>shlex.quote()</code>]] function can be used to
| |
− | properly escape whitespace and special characters in strings that
| |
− | are going to be used to construct shell commands.
| |
| | | |
| | | |
第1,345行: |
第501行: |
| <div id="callback-handles" class="section"> | | <div id="callback-handles" class="section"> |
| | | |
− | == Callback Handles == | + | == 回调句柄 == |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>Handle</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Handle</span></span></dt> |
− | <dd><p>A callback wrapper object returned by [[#asyncio.loop.call_soon|<code>loop.call_soon()</code>]], | + | <dd><p>[[#asyncio.loop.call_soon|loop.call_soon()]], [[#asyncio.loop.call_soon_threadsafe|loop.call_soon_threadsafe()]] 返回的回调包装对象。</p> |
− | [[#asyncio.loop.call_soon_threadsafe|<code>loop.call_soon_threadsafe()</code>]].</p> | |
| <dl> | | <dl> |
− | <dt><code>cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">cancel</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Cancel the callback. If the callback has already been canceled | + | <dd><p>取消回调。 如果回调已经被取消或执行,则此方法无效。</p></dd></dl> |
− | or executed, this method has no effect.</p></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt><code>cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">cancelled</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Return <code>True</code> if the callback was cancelled.</p> | + | <dd><p>如果回调被取消,则返回 <code>True</code>。</p> |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | + | <p><span class="versionmodified added">3.7 版中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
第1,367行: |
第521行: |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>TimerHandle</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">TimerHandle</span></span></dt> |
− | <dd><p>A callback wrapper object returned by [[#asyncio.loop.call_later|<code>loop.call_later()</code>]], | + | <dd><p>[[#asyncio.loop.call_later|loop.call_later()]] 和 [[#asyncio.loop.call_at|loop.call_at()]] 返回的回调包装对象。</p> |
− | and [[#asyncio.loop.call_at|<code>loop.call_at()</code>]].</p>
| + | <p>此类是 [[#asyncio.Handle|Handle]] 的子类。</p> |
− | <p>This class is a subclass of [[#asyncio.Handle|<code>Handle</code>]].</p> | |
| <dl> | | <dl> |
− | <dt><code>when</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">when</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Return a scheduled callback time as [[../functions#float|<code>float</code>]] seconds.</p> | + | <dd><p>将预定的回调时间返回为 [[../functions#float|float]] 秒。</p> |
− | <p>The time is an absolute timestamp, using the same time | + | <p>时间是绝对时间戳,使用与 [[#asyncio.loop.time|loop.time()]] 相同的时间参考。</p> |
− | reference as [[#asyncio.loop.time|<code>loop.time()</code>]].</p>
| |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | + | <p><span class="versionmodified added">3.7 版中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
第1,387行: |
第539行: |
| <div id="server-objects" class="section"> | | <div id="server-objects" class="section"> |
| | | |
− | == Server Objects == | + | == 服务器对象 == |
| | | |
− | Server objects are created by [[#asyncio.loop.create_server|<code>loop.create_server()</code>]],
| + | 服务器对象由 <code>loop.create_server()</code>、<code>loop.create_unix_server()</code>、<code>start_server()</code> 和 <code>start_unix_server()</code> 函数创建。 |
− | [[#asyncio.loop.create_unix_server|<code>loop.create_unix_server()</code>]], [[../asyncio-stream#asyncio|<code>start_server()</code>]],
| |
− | and [[../asyncio-stream#asyncio|<code>start_unix_server()</code>]] functions.
| |
| | | |
− | Do not instantiate the class directly.
| + | 不要直接实例化类。 |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>Server</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">Server</span></span></dt> |
− | <dd><p>''Server'' objects are asynchronous context managers. When used in an | + | <dd><p>''Server'' 对象是异步上下文管理器。 在 <code>async with</code> 语句中使用时,可以保证在 <code>async with</code> 语句完成时服务器对象已关闭且不接受新连接:</p> |
− | <code>async with</code> statement, it's guaranteed that the Server object is | |
− | closed and not accepting new connections when the <code>async with</code>
| |
− | statement is completed:</p>
| |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
| | | |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>srv = await loop.create_server(...) | + | <syntaxhighlight lang="python3">srv = await loop.create_server(...) |
| | | |
| async with srv: | | async with srv: |
| # some code | | # some code |
| | | |
− | # At this point, srv is closed and no longer accepts new connections.</pre> | + | # At this point, srv is closed and no longer accepts new connections.</syntaxhighlight> |
| | | |
| </div> | | </div> |
第1,417行: |
第564行: |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>Server object is an asynchronous context manager since Python 3.7.</p> | + | <p><span class="versionmodified changed"> 3.7 版更改:</span>Server 对象是自 Python 3.7 以来的异步上下文管理器。</p> |
| | | |
| </div> | | </div> |
| <dl> | | <dl> |
− | <dt><code>close</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Stop serving: close listening sockets and set the [[#asyncio.Server.sockets|<code>sockets</code>]]
| + | <dd><p>停止服务:关闭监听套接字并将 [[#asyncio.Server.sockets|sockets]] 属性设置为 <code>None</code>。</p> |
− | attribute to <code>None</code>.</p>
| + | <p>代表现有传入客户端连接的套接字保持打开状态。</p> |
− | <p>The sockets that represent existing incoming client connections
| + | <p>服务器异步关闭,使用<code>wait_closed()</code>协程等待服务器关闭。</p></dd></dl> |
− | are left open.</p>
| |
− | <p>The server is closed asynchronously, use the [[#asyncio.Server.wait_closed|<code>wait_closed()</code>]]
| |
− | coroutine to wait until the server is closed.</p></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt><code>get_loop</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
| |
− | <dd><p>Return the event loop associated with the server object.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p>
| |
− | | |
− | </div></dd></dl>
| |
− | | |
− | <dl>
| |
− | <dt>''coroutine'' <code>start_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
| |
− | <dd><p>Start accepting connections.</p> | |
− | <p>This method is idempotent, so it can be called when
| |
− | the server is already being serving.</p>
| |
− | <p>The ''start_serving'' keyword-only parameter to
| |
− | [[#asyncio.loop.create_server|<code>loop.create_server()</code>]] and | |
− | [[../asyncio-stream#asyncio|<code>asyncio.start_server()</code>]] allows creating a Server object
| |
− | that is not accepting connections initially. In this case
| |
− | <code>Server.start_serving()</code>, or [[#asyncio.Server.serve_forever|<code>Server.serve_forever()</code>]] can be used
| |
− | to make the Server start accepting connections.</p>
| |
− | <div class="versionadded">
| |
− | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | |
− | | |
− | </div></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt>''coroutine'' <code>serve_forever</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">get_loop</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Start accepting connections until the coroutine is cancelled. | + | <dd><p>返回与服务器对象关联的事件循环。</p> |
− | Cancellation of <code>serve_forever</code> task causes the server
| |
− | to be closed.</p>
| |
− | <p>This method can be called if the server is already accepting
| |
− | connections. Only one <code>serve_forever</code> task can exist per
| |
− | one ''Server'' object.</p>
| |
− | <p>Example:</p>
| |
− | <div class="highlight-python3 notranslate">
| |
− | | |
− | <div class="highlight">
| |
− | | |
− | <pre>async def client_connected(reader, writer):
| |
− | # Communicate with the client with
| |
− | # reader/writer streams. For example:
| |
− | await reader.readline()
| |
− | | |
− | async def main(host, port):
| |
− | srv = await asyncio.start_server(
| |
− | client_connected, host, port)
| |
− | await srv.serve_forever()
| |
− | | |
− | asyncio.run(main('127.0.0.1', 0))</pre>
| |
− | | |
− | </div>
| |
− | | |
− | </div>
| |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | + | <p><span class="versionmodified added">3.7 版中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt><code>is_serving</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">is_serving</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> |
− | <dd><p>Return <code>True</code> if the server is accepting new connections.</p> | + | <dd><p>如果服务器正在接受新连接,则返回 <code>True</code>。</p> |
| <div class="versionadded"> | | <div class="versionadded"> |
| | | |
− | <p><span class="versionmodified added">3.7 新版功能.</span></p> | + | <p><span class="versionmodified added">3.7 版中的新功能。</span></p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt>''coroutine'' <code>wait_closed</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt> | + | <dt><span class="sig-name descname"><span class="pre">sockets</span></span></dt> |
− | <dd><p>Wait until the [[#asyncio.Server.close|<code>close()</code>]] method completes.</p></dd></dl>
| + | <dd><p>服务器正在侦听的 [[../socket#socket|socket.socket]] 对象列表。</p> |
− | | |
− | <dl>
| |
− | <dt><code>sockets</code></dt>
| |
− | <dd><p>List of [[../socket#socket|<code>socket.socket</code>]] objects the server is listening on.</p> | |
| <div class="versionchanged"> | | <div class="versionchanged"> |
| | | |
− | <p><span class="versionmodified changed">在 3.7 版更改: </span>Prior to Python 3.7 <code>Server.sockets</code> used to return an | + | <p><span class="versionmodified changed"> 3.7 版更改: </span> Python 3.7 之前 <code>Server.sockets</code> 用于直接返回服务器套接字的内部列表。 在 3.7 中,会返回该列表的副本。</p> |
− | internal list of server sockets directly. In 3.7 a copy
| |
− | of that list is returned.</p>
| |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
第1,519行: |
第606行: |
| | | |
| <span id="asyncio-event-loops"></span> | | <span id="asyncio-event-loops"></span> |
− | == Event Loop Implementations == | + | == 事件循环实现 == |
| | | |
− | asyncio ships with two different event loop implementations: | + | asyncio 附带两种不同的事件循环实现:[[#asyncio.SelectorEventLoop|SelectorEventLoop]] 和 [[#asyncio.ProactorEventLoop|ProactorEventLoop]]。 |
− | [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]] and [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]]. | |
| | | |
− | By default asyncio is configured to use [[#asyncio.SelectorEventLoop|<code>SelectorEventLoop</code>]]
| + | 默认情况下,asyncio 配置为在 Unix 上使用 [[#asyncio.SelectorEventLoop|SelectorEventLoop]],在 Windows 上使用 [[#asyncio.ProactorEventLoop|ProactorEventLoop]]。 |
− | on Unix and [[#asyncio.ProactorEventLoop|<code>ProactorEventLoop</code>]] on Windows.
| |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>SelectorEventLoop</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">SelectorEventLoop</span></span></dt> |
− | <dd><p>An event loop based on the [[../selectors#module-selectors|<code>selectors</code>]] module.</p> | + | <dd><p>基于 [[../selectors#module-selectors|选择器]] 模块的事件循环。</p> |
− | <p>Uses the most efficient ''selector'' available for the given | + | <p>使用给定平台可用的最有效的 ''选择器'' 。 也可以手动配置要使用的确切选择器实现:</p> |
− | platform. It is also possible to manually configure the
| |
− | exact selector implementation to be used:</p>
| |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
| | | |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>import asyncio | + | <syntaxhighlight lang="python3">import asyncio |
| import selectors | | import selectors |
| | | |
| selector = selectors.SelectSelector() | | selector = selectors.SelectSelector() |
| loop = asyncio.SelectorEventLoop(selector) | | loop = asyncio.SelectorEventLoop(selector) |
− | asyncio.set_event_loop(loop)</pre> | + | asyncio.set_event_loop(loop)</syntaxhighlight> |
| | | |
| </div> | | </div> |
| | | |
− | </div> | + | </div></dd></dl> |
− | <p>[[../intro#availability|<span class="std std-ref">Availability</span>]]: Unix, Windows.</p></dd></dl>
| |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>ProactorEventLoop</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">ProactorEventLoop</span></span></dt> |
− | <dd><p>An event loop for Windows that uses "I/O Completion Ports" (IOCP).</p> | + | <dd><p>使用“I/O 完成端口”(IOCP) 的 Windows 事件循环。</p> |
− | <p>[[../intro#availability|<span class="std std-ref">Availability</span>]]: Windows.</p>
| |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | <p>参见</p> | + | <p>也可以看看</p> |
− | <p>[https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports MSDN documentation on I/O Completion Ports].</p> | + | <p>[https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports 关于 I/O 完成端口的 MSDN 文档] 。</p> |
| | | |
| </div></dd></dl> | | </div></dd></dl> |
| | | |
| <dl> | | <dl> |
− | <dt>''class'' <code>asyncio.</code><code>AbstractEventLoop</code></dt> | + | <dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">asyncio.</span></span><span class="sig-name descname"><span class="pre">AbstractEventLoop</span></span></dt> |
− | <dd><p>Abstract base class for asyncio-compliant event loops.</p> | + | <dd><p>异步兼容事件循环的抽象基类。</p> |
− | <p>The [[#asyncio-event-loop|<span class="std std-ref">Event Loop Methods</span>]] section lists all | + | <p>[[#asyncio-event-loop|Event Loop Methods]] 部分列出了 <code>AbstractEventLoop</code> 的替代实现应该定义的所有方法。</p></dd></dl> |
− | methods that an alternative implementation of <code>AbstractEventLoop</code>
| |
− | should have defined.</p></dd></dl>
| |
| | | |
| | | |
第1,571行: |
第650行: |
| <div id="examples" class="section"> | | <div id="examples" class="section"> |
| | | |
− | == Examples == | + | == 例子 == |
| | | |
− | Note that all examples in this section '''purposefully''' show how
| + | 请注意,本节 '''有意''' 中的所有示例都展示了如何使用低级事件循环 API,例如 [[#asyncio.loop.run_forever|loop.run_forever()]] 和 [[#asyncio.loop.call_soon|loop.call_soon()]] ]。 现代 asyncio 应用程序很少需要以这种方式编写; 考虑使用像 [[../asyncio-task#asyncio|asyncio.run()]] 这样的高级函数。 |
− | to use the low-level event loop APIs, such as [[#asyncio.loop.run_forever|<code>loop.run_forever()</code>]]
| |
− | and [[#asyncio.loop.call_soon|<code>loop.call_soon()</code>]]. Modern asyncio applications rarely
| |
− | need to be written this way; consider using the high-level functions
| |
− | like [[../asyncio-task#asyncio|<code>asyncio.run()</code>]].
| |
| | | |
| <div id="hello-world-with-call-soon" class="section"> | | <div id="hello-world-with-call-soon" class="section"> |
第1,584行: |
第659行: |
| === Hello World with call_soon() === | | === Hello World with call_soon() === |
| | | |
− | An example using the [[#asyncio.loop.call_soon|<code>loop.call_soon()</code>]] method to schedule a
| + | 使用 [[#asyncio.loop.call_soon|loop.call_soon()]] 方法安排回调的示例。 回调显示 <code>"Hello World"</code> 然后停止事件循环: |
− | callback. The callback displays <code>"Hello World"</code> and then stops the
| |
− | event loop:
| |
| | | |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
第1,592行: |
第665行: |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>import asyncio | + | <syntaxhighlight lang="python3">import asyncio |
| | | |
| def hello_world(loop): | | def hello_world(loop): |
− | """A callback to print 'Hello World' and stop the event loop""" | + | """A callback to print 'Hello World' and stop the event loop""" |
| print('Hello World') | | print('Hello World') |
| loop.stop() | | loop.stop() |
第1,608行: |
第681行: |
| loop.run_forever() | | loop.run_forever() |
| finally: | | finally: |
− | loop.close()</pre> | + | loop.close()</syntaxhighlight> |
| | | |
| </div> | | </div> |
第1,615行: |
第688行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | A similar [[../asyncio-task#coroutine|<span class="std std-ref">Hello World</span>]]
| + | 使用协程和 [[../asyncio-task#asyncio|run()]] 函数创建的类似 [[../asyncio-task#coroutine|Hello World]] 示例。 |
− | example created with a coroutine and the [[../asyncio-task#asyncio|<code>run()</code>]] function.
| |
| | | |
| | | |
第1,627行: |
第699行: |
| | | |
| <span id="asyncio-example-call-later"></span> | | <span id="asyncio-example-call-later"></span> |
− | === Display the current date with call_later() === | + | === 使用 call_later() 显示当前日期 === |
| | | |
− | An example of a callback displaying the current date every second. The
| + | 每秒显示当前日期的回调示例。 回调使用 [[#asyncio.loop.call_later|loop.call_later()]] 方法在 5 秒后重新调度自身,然后停止事件循环: |
− | callback uses the [[#asyncio.loop.call_later|<code>loop.call_later()</code>]] method to reschedule itself
| |
− | after 5 seconds, and then stops the event loop:
| |
| | | |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
第1,637行: |
第707行: |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>import asyncio | + | <syntaxhighlight lang="python3">import asyncio |
| import datetime | | import datetime |
| | | |
| def display_date(end_time, loop): | | def display_date(end_time, loop): |
| print(datetime.datetime.now()) | | print(datetime.datetime.now()) |
− | if (loop.time() + 1.0) < end_time: | + | if (loop.time() + 1.0) < end_time: |
| loop.call_later(1, display_date, end_time, loop) | | loop.call_later(1, display_date, end_time, loop) |
| else: | | else: |
第1,657行: |
第727行: |
| loop.run_forever() | | loop.run_forever() |
| finally: | | finally: |
− | loop.close()</pre> | + | loop.close()</syntaxhighlight> |
| | | |
| </div> | | </div> |
第1,664行: |
第734行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | A similar [[../asyncio-task#asyncio-example-sleep|<span class="std std-ref">current date</span>]] example
| + | 使用协程和 [[../asyncio-task#asyncio|run()]] 函数创建的类似 <span class="xref std std-ref"> 当前日期 </span> 示例。 |
− | created with a coroutine and the [[../asyncio-task#asyncio|<code>run()</code>]] function.
| |
| | | |
| | | |
第1,676行: |
第745行: |
| | | |
| <span id="asyncio-example-watch-fd"></span> | | <span id="asyncio-example-watch-fd"></span> |
− | === Watch a file descriptor for read events === | + | === 观察文件描述符以获取读取事件 === |
| | | |
− | Wait until a file descriptor received some data using the
| + | 等到文件描述符使用 [[#asyncio.loop.add_reader|loop.add_reader()]] 方法接收到一些数据,然后关闭事件循环: |
− | [[#asyncio.loop.add_reader|<code>loop.add_reader()</code>]] method and then close the event loop: | |
| | | |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
第1,685行: |
第753行: |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>import asyncio | + | <syntaxhighlight lang="python3">import asyncio |
| from socket import socketpair | | from socket import socketpair |
| | | |
第1,695行: |
第763行: |
| def reader(): | | def reader(): |
| data = rsock.recv(100) | | data = rsock.recv(100) |
− | print("Received:", data.decode()) | + | print("Received:", data.decode()) |
| | | |
| # We are done: unregister the file descriptor | | # We are done: unregister the file descriptor |
第1,716行: |
第784行: |
| rsock.close() | | rsock.close() |
| wsock.close() | | wsock.close() |
− | loop.close()</pre> | + | loop.close()</syntaxhighlight> |
| | | |
| </div> | | </div> |
第1,723行: |
第791行: |
| <div class="admonition seealso"> | | <div class="admonition seealso"> |
| | | |
− | 参见
| + | 也可以看看 |
| | | |
− | * A similar [[../asyncio-protocol#asyncio-example-create-connection|<span class="std std-ref">example</span>]] using transports, protocols, and the [[#asyncio.loop.create_connection|<code>loop.create_connection()</code>]] method. | + | * 使用传输、协议和 <code>loop.create_connection()</code> 方法的类似 [[../asyncio-protocol#asyncio-example-create-connection|示例]] 。 |
− | * Another similar [[../asyncio-stream#asyncio-example-create-connection-streams|<span class="std std-ref">example</span>]] using the high-level [[../asyncio-stream#asyncio|<code>asyncio.open_connection()</code>]] function and streams. | + | * 另一个类似的 [[../asyncio-stream#asyncio-example-create-connection-streams|示例]] 使用高级 <code>asyncio.open_connection()</code> 函数和流。 |
| | | |
| | | |
第1,735行: |
第803行: |
| | | |
| <span id="asyncio-example-unix-signals"></span> | | <span id="asyncio-example-unix-signals"></span> |
− | === Set signal handlers for SIGINT and SIGTERM === | + | === 为 SIGINT 和 SIGTERM 设置信号处理程序 === |
| | | |
− | (This <code>signals</code> example only works on Unix.)
| + | (此 <code>signals</code> 示例仅适用于 Unix。) |
| | | |
− | Register handlers for signals <code>SIGINT</code> and <code>SIGTERM</code>
| + | 使用 [[#asyncio.loop.add_signal_handler|loop.add_signal_handler()]] 方法为信号 <code>SIGINT</code> 和 <code>SIGTERM</code> 注册处理程序: |
− | using the [[#asyncio.loop.add_signal_handler|<code>loop.add_signal_handler()</code>]] method:
| |
| | | |
| <div class="highlight-python3 notranslate"> | | <div class="highlight-python3 notranslate"> |
第1,746行: |
第813行: |
| <div class="highlight"> | | <div class="highlight"> |
| | | |
− | <pre>import asyncio | + | <syntaxhighlight lang="python3">import asyncio |
| import functools | | import functools |
| import os | | import os |
第1,752行: |
第819行: |
| | | |
| def ask_exit(signame, loop): | | def ask_exit(signame, loop): |
− | print("got signal %s: exit" % signame) | + | print("got signal %s: exit" % signame) |
| loop.stop() | | loop.stop() |
| | | |
第1,765行: |
第832行: |
| await asyncio.sleep(3600) | | await asyncio.sleep(3600) |
| | | |
− | print("Event loop running for 1 hour, press Ctrl+C to interrupt.") | + | print("Event loop running for 1 hour, press Ctrl+C to interrupt.") |
− | print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.") | + | print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.") |
| + | |
| + | asyncio.run(main())</syntaxhighlight> |
| | | |
− | asyncio.run(main())</pre>
| + | </div> |
| | | |
| </div> | | </div> |
第1,777行: |
第846行: |
| | | |
| </div> | | </div> |
| + | <div class="clearer"> |
| + | |
| + | |
| | | |
| </div> | | </div> |
| | | |
− | [[Category:Python 3.9 中文文档]] | + | [[Category:Python 3.9 文档]] |