# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2026 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-07-15 16:14+0000\n" "PO-Revision-Date: 2026-05-08 17:17+0000\n" "Last-Translator: Rafael Fontenelle , 2026\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/asyncio-eventloop.rst:8 msgid "Event loop" msgstr "事件循环" #: ../../library/asyncio-eventloop.rst:10 msgid "" "**Source code:** :source:`Lib/asyncio/events.py`, " ":source:`Lib/asyncio/base_events.py`" msgstr "" "**源代码:** :source:`Lib/asyncio/events.py`, " ":source:`Lib/asyncio/base_events.py`" #: ../../library/asyncio-eventloop.rst:16 msgid "Preface" msgstr "前言" #: ../../library/asyncio-eventloop.rst:17 msgid "" "The event loop is the core of every asyncio application. Event loops run " "asynchronous tasks and callbacks, perform network IO operations, and run " "subprocesses." msgstr "事件循环是每个 asyncio 应用的核心。 事件循环会运行异步任务和回调,执行网络 IO 操作,以及运行子进程。" #: ../../library/asyncio-eventloop.rst:21 msgid "" "Application developers should typically use the high-level asyncio " "functions, such as :func:`asyncio.run`, 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." msgstr "" "应用开发者通常应当使用高层级的 asyncio 函数,例如 :func:`asyncio.run`,应当很少有必要引用循环对象或调用其方法。 " "本节所针对的主要是低层级代码、库和框架的编写者,他们需要更细致地控制事件循环行为。" #: ../../library/asyncio-eventloop.rst:28 msgid "Obtaining the Event Loop" msgstr "获取事件循环" #: ../../library/asyncio-eventloop.rst:29 msgid "" "The following low-level functions can be used to get, set, or create an " "event loop:" msgstr "以下低层级函数可被用于获取、设置或创建事件循环:" #: ../../library/asyncio-eventloop.rst:34 msgid "Return the running event loop in the current OS thread." msgstr "返回当前 OS 线程中正在运行的事件循环。" #: ../../library/asyncio-eventloop.rst:36 msgid "Raise a :exc:`RuntimeError` if there is no running event loop." msgstr "如果没有正在运行的事件循环则会引发 :exc:`RuntimeError`。" #: ../../library/asyncio-eventloop.rst:38 msgid "This function can only be called from a coroutine or a callback." msgstr "此函数只能由协程或回调来调用。" #: ../../library/asyncio-eventloop.rst:44 msgid "Get the current event loop." msgstr "获取当前事件循环。" #: ../../library/asyncio-eventloop.rst:46 msgid "" "When called from a coroutine or a callback (e.g. scheduled with call_soon or" " similar API), this function will always return the running event loop." msgstr "当在协程或回调中被调用时(例如通过 call_soon 或类似 API 加入计划任务),此函数将始终返回正在运行的事件循环。" #: ../../library/asyncio-eventloop.rst:50 msgid "" "If there is no running event loop set, the function will return the result " "of the ``get_event_loop_policy().get_event_loop()`` call." msgstr "" "如果没有设置正在运行的事件循环,此函数将返回 ``get_event_loop_policy().get_event_loop()`` 调用的结果。" #: ../../library/asyncio-eventloop.rst:53 msgid "" "Because this function has rather complex behavior (especially when custom " "event loop policies are in use), using the :func:`get_running_loop` function" " is preferred to :func:`get_event_loop` in coroutines and callbacks." msgstr "" "由于此函数具有相当复杂的行为(特别是在使用了自定义事件循环策略的时候),更推荐在协程和回调中使用 :func:`get_running_loop` " "函数而非 :func:`get_event_loop`。" #: ../../library/asyncio-eventloop.rst:58 msgid "" "As noted above, consider using the higher-level :func:`asyncio.run` " "function, instead of using these lower level functions to manually create " "and close an event loop." msgstr "如上文所说,请考虑使用高层级的 :func:`asyncio.run` 函数,而不是使用这些低层级的函数来手动创建和关闭事件循环。" #: ../../library/asyncio-eventloop.rst:62 msgid "Raises a :exc:`RuntimeError` if there is no current event loop." msgstr "如果没有当前事件循环则会引发 :exc:`RuntimeError`。" #: ../../library/asyncio-eventloop.rst:67 msgid "" "The :mod:`!asyncio` policy system is deprecated and will be removed in " "Python 3.16; from there on, this function will return the current running " "event loop if present else it will return the loop set by " ":func:`set_event_loop`." msgstr "" ":mod:`!asyncio` 策略系统已弃用,将在 Python 3.16 " "中删除;从那时起,此函数将返回当前正在运行的事件循环(如果存在),否则它将返回由 :func:`set_event_loop` 设置的循环。" #: ../../library/asyncio-eventloop.rst:74 msgid "Set *loop* as the current event loop for the current OS thread." msgstr "将 *loop* 设为当前 OS 线程的当前事件循环。" #: ../../library/asyncio-eventloop.rst:78 msgid "Create and return a new event loop object." msgstr "创建并返回一个新的事件循环对象。" #: ../../library/asyncio-eventloop.rst:80 msgid "" "Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`, " "and :func:`new_event_loop` functions can be altered by :ref:`setting a " "custom event loop policy `." msgstr "" "请注意 :func:`get_event_loop`, :func:`set_event_loop` 以及 :func:`new_event_loop`" " 函数的行为可以通过 :ref:`设置自定义事件循环策略 ` 来改变。" #: ../../library/asyncio-eventloop.rst:86 msgid "Contents" msgstr "目录" #: ../../library/asyncio-eventloop.rst:87 msgid "This documentation page contains the following sections:" msgstr "本文档包含下列小节:" #: ../../library/asyncio-eventloop.rst:89 msgid "" "The `Event Loop Methods`_ section is the reference documentation of the " "event loop APIs;" msgstr "`Event Loop Methods`_ 一节是事件循环 API 的参考文档;" #: ../../library/asyncio-eventloop.rst:92 msgid "" "The `Callback Handles`_ section documents the :class:`Handle` and " ":class:`TimerHandle` instances which are returned from scheduling methods " "such as :meth:`loop.call_soon` and :meth:`loop.call_later`;" msgstr "" "`回调处理`_ 章节是从调度方法 例如 :meth:`loop.call_soon` 和 :meth:`loop.call_later` 中返回 " ":class:`Handle` 和 :class:`TimerHandle` 实例的文档。" #: ../../library/asyncio-eventloop.rst:96 msgid "" "The `Server Objects`_ section documents types returned from event loop " "methods like :meth:`loop.create_server`;" msgstr "`Server Objects`_ 小节记录了从事件循环方法返回的类型,比如 :meth:`loop.create_server`;" #: ../../library/asyncio-eventloop.rst:99 msgid "" "The `Event Loop Implementations`_ section documents the " ":class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;" msgstr "" "`Event Loop Implementations`_ 章节记录了 :class:`SelectorEventLoop` 和 " ":class:`ProactorEventLoop` 类;" #: ../../library/asyncio-eventloop.rst:102 msgid "" "The `Examples`_ section showcases how to work with some event loop APIs." msgstr "`Examples`_ 小节展示了如何使用某些事件循环 API。" #: ../../library/asyncio-eventloop.rst:109 msgid "Event loop methods" msgstr "事件循环方法集" #: ../../library/asyncio-eventloop.rst:111 msgid "Event loops have **low-level** APIs for the following:" msgstr "事件循环有下列 **低级** APIs:" #: ../../library/asyncio-eventloop.rst:119 msgid "Running and stopping the loop" msgstr "运行和停止循环" #: ../../library/asyncio-eventloop.rst:123 msgid "Run until the *future* (an instance of :class:`Future`) has completed." msgstr "运行直到 *future* ( :class:`Future` 的实例 ) 被完成。" #: ../../library/asyncio-eventloop.rst:126 msgid "" "If the argument is a :ref:`coroutine object ` it is implicitly " "scheduled to run as a :class:`asyncio.Task`." msgstr "如果参数是 :ref:`协程对象 ` 则将被隐式调度作为 :class:`asyncio.Task` 来运行。" #: ../../library/asyncio-eventloop.rst:129 msgid "Return the Future's result or raise its exception." msgstr "返回 Future 的结果 或者引发相关异常。" #: ../../library/asyncio-eventloop.rst:133 msgid "Run the event loop until :meth:`stop` is called." msgstr "运行事件循环直到 :meth:`stop` 被调用。" #: ../../library/asyncio-eventloop.rst:135 msgid "" "If :meth:`stop` is called before :meth:`run_forever` is called, the loop " "will poll the I/O selector once with a timeout of zero, run all callbacks " "scheduled in response to I/O events (and those that were already scheduled)," " and then exit." msgstr "" "如果 :meth:`stop` 在调用 :meth:`run_forever` 之前被调用,循环将轮询一次 I/O " "选择器并设置超时为零,再运行所有已加入计划任务的回调来响应 I/O 事件(以及已加入计划任务的事件),然后退出。" #: ../../library/asyncio-eventloop.rst:140 msgid "" "If :meth:`stop` is called while :meth:`run_forever` 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 :meth:`run_forever` or :meth:`run_until_complete` is " "called." msgstr "" "如果 :meth:`stop` 在 :meth:`run_forever` 运行期间被调用,循环将运行当前批次的回调然后退出。 " "请注意在此情况下由回调加入计划任务的新回调将不会运行;它们将会在下次 :meth:`run_forever` 或 " ":meth:`run_until_complete` 被调用时运行。" #: ../../library/asyncio-eventloop.rst:148 msgid "Stop the event loop." msgstr "停止事件循环。" #: ../../library/asyncio-eventloop.rst:152 msgid "Return ``True`` if the event loop is currently running." msgstr "返回 ``True`` 如果事件循环当前正在运行。" #: ../../library/asyncio-eventloop.rst:156 msgid "Return ``True`` if the event loop was closed." msgstr "如果事件循环已经被关闭则返回 ``True``。" #: ../../library/asyncio-eventloop.rst:160 msgid "Close the event loop." msgstr "关闭事件循环。" #: ../../library/asyncio-eventloop.rst:162 msgid "" "The loop must not be running when this function is called. Any pending " "callbacks will be discarded." msgstr "当这个函数被调用的时候,循环必须处于非运行状态。待处理的回调将被丢弃。" #: ../../library/asyncio-eventloop.rst:165 msgid "" "This method clears all queues and shuts down the executor, but does not wait" " for the executor to finish." msgstr "此方法清除所有的队列并立即关闭执行器,不会等待执行器完成。" #: ../../library/asyncio-eventloop.rst:168 msgid "" "This method is idempotent and irreversible. No other methods should be " "called after the event loop is closed." msgstr "这个方法是幂等的和不可逆的。事件循环关闭后,不应调用其他方法。" #: ../../library/asyncio-eventloop.rst:174 msgid "" "Schedule all currently open :term:`asynchronous generator` objects to close " "with an :meth:`~agen.aclose` 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." msgstr "" "安排所有当前打开的 :term:`asynchronous generator` 对象通过 :meth:`~agen.aclose` 调用来关闭。 " "在调用此方法后,如果有新的异步生成器被迭代则事件循环将会发出警告。 这应当被用来可靠地最终化所有已加入计划任务的异步生成器。" #: ../../library/asyncio-eventloop.rst:180 msgid "" "Note that there is no need to call this function when :func:`asyncio.run` is" " used." msgstr "请注意当使用 :func:`asyncio.run` 时不必调用此函数。" #: ../../library/asyncio-eventloop.rst:183 #: ../../library/asyncio-eventloop.rst:1397 #: ../../library/asyncio-eventloop.rst:1859 msgid "Example::" msgstr "示例::" #: ../../library/asyncio-eventloop.rst:185 msgid "" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.run_until_complete(loop.shutdown_asyncgens())\n" " loop.close()" msgstr "" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.run_until_complete(loop.shutdown_asyncgens())\n" " loop.close()" #: ../../library/asyncio-eventloop.rst:196 msgid "" "Schedule the closure of the default executor and wait for it to join all of " "the threads in the :class:`~concurrent.futures.ThreadPoolExecutor`. Once " "this method has been called, using the default executor with " ":meth:`loop.run_in_executor` will raise a :exc:`RuntimeError`." msgstr "" "安排默认执行器的关闭并等待它合并 :class:`~concurrent.futures.ThreadPoolExecutor` 中的所有线程。 " "一旦此方法被调用,将默认执行器与 :meth:`loop.run_in_executor` 一起使用将引发 :exc:`RuntimeError`。" #: ../../library/asyncio-eventloop.rst:202 msgid "" "The *timeout* parameter specifies the amount of time (in :class:`float` " "seconds) the executor will be given to finish joining. With the default, " "``None``, the executor is allowed an unlimited amount of time." msgstr "" "*timeout* 形参指定提供给执行器结束合并的时间限制(为 :class:`float` 形式的秒数)。 在默认情况下,该值为 " "``None``,即允许执行器无时间限制地执行。" #: ../../library/asyncio-eventloop.rst:207 msgid "" "If the *timeout* is reached, a :exc:`RuntimeWarning` is emitted and the " "default executor is terminated without waiting for its threads to finish " "joining." msgstr "如果达到了 *timeout*,将会发出 :exc:`RuntimeWarning` 并且默认执行器将会终结而不等待其线程结束合并。" #: ../../library/asyncio-eventloop.rst:213 msgid "" "Do not call this method when using :func:`asyncio.run`, as the latter " "handles default executor shutdown automatically." msgstr "当使用 :func:`asyncio.run` 时不要调用此方法,因为它会自动处理默认执行器的关闭。" #: ../../library/asyncio-eventloop.rst:218 msgid "Added the *timeout* parameter." msgstr "增加了 *timeout* 形参。" #: ../../library/asyncio-eventloop.rst:222 msgid "Scheduling callbacks" msgstr "安排回调" #: ../../library/asyncio-eventloop.rst:226 msgid "" "Schedule the *callback* :term:`callback` to be called with *args* arguments " "at the next iteration of the event loop." msgstr "安排 *callback* :term:`callback` 在事件循环的下一次迭代时附带 *args* 参数被调用。" #: ../../library/asyncio-eventloop.rst:229 msgid "" "Return an instance of :class:`asyncio.Handle`, which can be used later to " "cancel the callback." msgstr "返回一个 :class:`asyncio.Handle` 的实例,可在此后被用来取消回调。" #: ../../library/asyncio-eventloop.rst:232 msgid "" "Callbacks are called in the order in which they are registered. Each " "callback will be called exactly once." msgstr "回调按其注册顺序被调用。每个回调仅被调用一次。" #: ../../library/asyncio-eventloop.rst:235 msgid "" "The optional keyword-only *context* argument specifies a custom " ":class:`contextvars.Context` for the *callback* to run in. Callbacks use the" " current context when no *context* is provided." msgstr "" "可选的仅限关键字参数 *context* 指定一个自定义的 :class:`contextvars.Context` 供 *callback* " "在其中运行。 当未提供 *context* 时回调将使用当前上下文。" #: ../../library/asyncio-eventloop.rst:239 msgid "Unlike :meth:`call_soon_threadsafe`, this method is not thread-safe." msgstr "与 :meth:`call_soon_threadsafe` 不同,此方法不是线程安全的。" #: ../../library/asyncio-eventloop.rst:243 msgid "" "A thread-safe variant of :meth:`call_soon`. When scheduling callbacks from " "another thread, this function *must* be used, since :meth:`call_soon` is not" " thread-safe." msgstr "" ":meth:`call_soon` 的线程安全版。 当从另一个线程安排回调时,*必须* 使用此函数,因为 :meth:`call_soon` " "不是线程安全的。" #: ../../library/asyncio-eventloop.rst:247 msgid "" "This function is safe to be called from a reentrant context or signal " "handler, however, it is not safe or fruitful to use the returned handle in " "such contexts." msgstr "此函数可以从一个重入上下文或信号处理器安全地调用,不过,在这样的上下文中使用所返回的句柄则不是安全或有益的。" #: ../../library/asyncio-eventloop.rst:250 msgid "" "Raises :exc:`RuntimeError` if called on a loop that's been closed. This can " "happen on a secondary thread when the main application is shutting down." msgstr "如果在已被关闭的循环上调用则会引发 :exc:`RuntimeError`。 这可能会在主应用程序被关闭时在二级线程上发生。" #: ../../library/asyncio-eventloop.rst:254 msgid "" "See the :ref:`concurrency and multithreading ` " "section of the documentation." msgstr "" "参见 :ref:`concurrency and multithreading ` 部分的文档。" #: ../../library/asyncio-eventloop.rst:257 #: ../../library/asyncio-eventloop.rst:314 #: ../../library/asyncio-eventloop.rst:340 msgid "" "The *context* keyword-only parameter was added. See :pep:`567` for more " "details." msgstr "加入仅限关键字形参 *context*。请参阅 :pep:`567` 查看更多细节。" #: ../../library/asyncio-eventloop.rst:265 msgid "" "Most :mod:`asyncio` scheduling functions don't allow passing keyword " "arguments. To do that, use :func:`functools.partial`::" msgstr "大多数 :mod:`asyncio` 的调度函数不允许传递关键字参数。为此,请使用 :func:`functools.partial`::" #: ../../library/asyncio-eventloop.rst:268 msgid "" "# will schedule \"print(\"Hello\", flush=True)\"\n" "loop.call_soon(\n" " functools.partial(print, \"Hello\", flush=True))" msgstr "" "# 将把 \"print(\"Hello\", flush=True)\" 加入计划任务\n" "loop.call_soon(\n" " functools.partial(print, \"Hello\", flush=True))" #: ../../library/asyncio-eventloop.rst:272 msgid "" "Using partial objects is usually more convenient than using lambdas, as " "asyncio can render partial objects better in debug and error messages." msgstr "使用 partial 对象通常比使用 lambda 更方便,asyncio 在调试和错误消息中能更好的呈现 partial 对象。" #: ../../library/asyncio-eventloop.rst:280 msgid "Scheduling delayed callbacks" msgstr "调度延迟回调" #: ../../library/asyncio-eventloop.rst:282 msgid "" "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." msgstr "事件循环提供安排调度函数在将来某个时刻调用的机制。事件循环使用单调时钟来跟踪时间。" #: ../../library/asyncio-eventloop.rst:289 msgid "" "Schedule *callback* to be called after the given *delay* number of seconds " "(can be either an int or a float)." msgstr "安排 *callback* 在给定的 *delay* 秒(可以是 int 或者 float)后被调用。" #: ../../library/asyncio-eventloop.rst:292 #: ../../library/asyncio-eventloop.rst:331 msgid "" "An instance of :class:`asyncio.TimerHandle` is returned which can be used to" " cancel the callback." msgstr "返回一个 :class:`asyncio.TimerHandle` 实例,该实例能用于取消回调。" #: ../../library/asyncio-eventloop.rst:295 msgid "" "*callback* will be called exactly once. If two callbacks are scheduled for " "exactly the same time, the order in which they are called is undefined." msgstr "*callback* 只被调用一次。如果两个回调被安排在同样的时间点,执行顺序未限定。" #: ../../library/asyncio-eventloop.rst:299 msgid "" "The optional positional *args* will be passed to the callback when it is " "called. Use :func:`functools.partial` :ref:`to pass keyword arguments " "` to *callback*." msgstr "" "可选的位置参数 *args* 将在回调被调用时传入。 使用 :func:`functools.partial` :ref:`将关键字参数 " "` 传给 *callback*。" #: ../../library/asyncio-eventloop.rst:304 msgid "" "An optional keyword-only *context* argument allows specifying a custom " ":class:`contextvars.Context` for the *callback* to run in. The current " "context is used when no *context* is provided." msgstr "" "可选的仅限关键字参数 *context* 允许 *callback* 运行在一个指定的自定义 :class:`contextvars.Context` " "对象中。如果没有提供 *context* ,则使用当前上下文。" #: ../../library/asyncio-eventloop.rst:310 msgid "" "For performance, callbacks scheduled with :meth:`loop.call_later` may run up" " to one clock-resolution early (see " "``time.get_clock_info('monotonic').resolution``)." msgstr "" "出于性能考虑,使用 :meth:`loop.call_later` 调度的回调函数可能会提前最多一个时钟分辨率的时间执行(具体精度可通过 " "``time.get_clock_info('monotonic').resolution`` 查看)。" #: ../../library/asyncio-eventloop.rst:318 msgid "" "In Python 3.7 and earlier with the default event loop implementation, the " "*delay* could not exceed one day. This has been fixed in Python 3.8." msgstr "在 Python 3.7 和更早版本的默认事件循环实现中, *delay* 不能超过一天。这在 Python 3.8 中已被修复。" #: ../../library/asyncio-eventloop.rst:325 msgid "" "Schedule *callback* to be called at the given absolute timestamp *when* (an " "int or a float), using the same time reference as :meth:`loop.time`." msgstr "" "安排 *callback* 在给定的绝对时间戳 *when* (int 或 float) 被调用,使用与 :meth:`loop.time` " "同样的时间参考。" #: ../../library/asyncio-eventloop.rst:329 msgid "This method's behavior is the same as :meth:`call_later`." msgstr "本方法的行为和 :meth:`call_later` 方法相同。" #: ../../library/asyncio-eventloop.rst:336 msgid "" "For performance, callbacks scheduled with :meth:`loop.call_at` may run up to" " one clock-resolution early (see " "``time.get_clock_info('monotonic').resolution``)." msgstr "" "出于性能考虑,使用 :meth:`loop.call_at` 调度的回调函数可能会提前最多一个时钟分辨率的时间执行(具体精度可通过 " "``time.get_clock_info('monotonic').resolution`` 查看)。" #: ../../library/asyncio-eventloop.rst:344 msgid "" "In Python 3.7 and earlier with the default event loop implementation, the " "difference between *when* and the current time could not exceed one day. " "This has been fixed in Python 3.8." msgstr "" "在 Python 3.7 和更早版本的默认事件循环实现中,*when* 和当前时间相差不能超过一天。 在 Python 3.8 中已被修复。" #: ../../library/asyncio-eventloop.rst:351 msgid "" "Return the current time, as a :class:`float` value, according to the event " "loop's internal monotonic clock." msgstr "根据事件循环内部的单调时钟,返回当前时间为一个 :class:`float` 值。" #: ../../library/asyncio-eventloop.rst:355 msgid "" "In Python 3.7 and earlier timeouts (relative *delay* or absolute *when*) " "should not exceed one day. This has been fixed in Python 3.8." msgstr "" "在 Python 3.7 和更早版本中超时 (相对的 *delay* 或绝对的 *when*) 不能超过一天。这在 Python 3.8 中已被修复。" #: ../../library/asyncio-eventloop.rst:361 msgid "The :func:`asyncio.sleep` function." msgstr ":func:`asyncio.sleep` 函数。" #: ../../library/asyncio-eventloop.rst:365 msgid "Creating futures and tasks" msgstr "创建 Future 和 Task" #: ../../library/asyncio-eventloop.rst:369 msgid "Create an :class:`asyncio.Future` object attached to the event loop." msgstr "创建一个附加到事件循环中的 :class:`asyncio.Future` 对象。" #: ../../library/asyncio-eventloop.rst:371 msgid "" "This is the preferred way to create Futures in asyncio. This lets third-" "party event loops provide alternative implementations of the Future object " "(with better performance or instrumentation)." msgstr "" "这是在 asyncio 中创建 Futures 的首选方式。这让第三方事件循环可以提供 Future 对象的替代实现 (更好的性能或者功能)。" #: ../../library/asyncio-eventloop.rst:379 msgid "" "Schedule the execution of :ref:`coroutine ` *coro*. Return a " ":class:`Task` object." msgstr "将 :ref:`协程 ` *coro* 的执行加入计划任务。 返回一个 :class:`Task` 对象。" #: ../../library/asyncio-eventloop.rst:382 msgid "" "Third-party event loops can use their own subclass of :class:`Task` for " "interoperability. In this case, the result type is a subclass of " ":class:`Task`." msgstr "" "第三方的事件循环可以使用它们自己的 :class:`Task` 子类来满足互操作性。这种情况下结果类型是一个 :class:`Task` 的子类。" #: ../../library/asyncio-eventloop.rst:386 msgid "" "The full function signature is largely the same as that of the :class:`Task`" " constructor (or factory) - all of the keyword arguments to this function " "are passed through to that interface." msgstr "完整函数签名与 :class:`Task` 构造器(或工厂函数)的大致相同 —— 所有传给此函数的关键字参数都会被传给该接口。" #: ../../library/asyncio-eventloop.rst:390 msgid "" "If the *name* argument is provided and not ``None``, it is set as the name " "of the task using :meth:`Task.set_name`." msgstr "如果提供了 *name* 参数且不为 ``None``,它会使用 :meth:`Task.set_name` 来设为任务的名称。" #: ../../library/asyncio-eventloop.rst:393 msgid "" "An optional keyword-only *context* argument allows specifying a custom " ":class:`contextvars.Context` for the *coro* to run in. The current context " "copy is created when no *context* is provided." msgstr "" "可选的 *context* 参数允许指定自定义的 :class:`contextvars.Context` 供 *coro* 运行。当未提供 " "*context* 时将创建当前上下文的副本。" #: ../../library/asyncio-eventloop.rst:397 msgid "" "An optional keyword-only *eager_start* argument allows specifying if the " "task should execute eagerly during the call to create_task, or be scheduled " "later. If *eager_start* is not passed the mode set by " ":meth:`loop.set_task_factory` will be used." msgstr "" "一个可选的只有关键字的 *eager_start* 参数允许指定任务是应该在调用 create_task 期间紧急执行,还是稍后调度。如果没有传递 " "*eager_start*,则会使用 :meth:`loop.set_task_factory` 设置的模式。" #: ../../library/asyncio-eventloop.rst:402 msgid "Added the *name* parameter." msgstr "添加了 *name* 参数。" #: ../../library/asyncio-eventloop.rst:405 msgid "Added the *context* parameter." msgstr "增加了 *context* 形参。" #: ../../library/asyncio-eventloop.rst:408 msgid "" "Added ``kwargs`` which passes on arbitrary extra parameters, including " "``name`` and ``context``." msgstr "增加了 ``kwargs``,它将传递任意附加形参,包括 ``name`` 和 ``context``。" #: ../../library/asyncio-eventloop.rst:411 msgid "" "Rolled back the change that passes on *name* and *context* (if it is None), " "while still passing on other arbitrary keyword arguments (to avoid breaking " "backwards compatibility with 3.13.3)." msgstr "" "撤回传递 *name* 和 *context* (如果其为 None) 的更改,虽然仍会传递其他任何关键字参数(以避免破坏与 3.13.3 " "的向下兼容)。" #: ../../library/asyncio-eventloop.rst:415 msgid "" "All *kwargs* are now passed on. The *eager_start* parameter works with eager" " task factories." msgstr "现在所有 *kwargs* 都会被传递。 *eager_start* 形参适用于主动型任务工厂。" #: ../../library/asyncio-eventloop.rst:420 msgid "Set a task factory that will be used by :meth:`loop.create_task`." msgstr "设置一个任务工厂,它将由 :meth:`loop.create_task` 来使用。" #: ../../library/asyncio-eventloop.rst:423 msgid "" "If *factory* is ``None`` the default task factory will be set. Otherwise, " "*factory* must be a *callable* with the signature matching ``(loop, coro, " "**kwargs)``, where *loop* is a reference to the active event loop, and " "*coro* is a coroutine object. The callable must pass on all *kwargs*, and " "return a :class:`asyncio.Task`-compatible object." msgstr "" "如果 *factory* 为 ``None`` 则将设置默认的任务工厂。在其他情况下,*factory* 必须是一个 *可调用对象* 且其签名要匹配 " "``(loop, coro, **kwargs)``,其中 *loop* 是一个指向活动事件循环的引用,而 *coro* 是一个协程对象。 " "该可调用对象必须传递所有 *kwargs*,并且返回一个 :class:`asyncio.Task` 兼容对象。" #: ../../library/asyncio-eventloop.rst:429 msgid "Required that all *kwargs* are passed on to :class:`asyncio.Task`." msgstr "要求所有 *kwargs* 被传递给 :class:`asyncio.Task`。" #: ../../library/asyncio-eventloop.rst:432 msgid "" "*name* is no longer passed to task factories. *context* is no longer passed " "to task factories if it is ``None``." msgstr "*name* 不再会被传递给任务工厂函数。如果其为 ``None`` 则 *context* 也不再会被传递给任务工厂函数。" #: ../../library/asyncio-eventloop.rst:436 msgid "" "*name* and *context* are now unconditionally passed on to task factories " "again." msgstr "现在 *name* 和 *context* 会被无条件地再次传递给任务工厂。" #: ../../library/asyncio-eventloop.rst:441 msgid "Return a task factory or ``None`` if the default one is in use." msgstr "返回一个任务工厂,或者如果是使用默认值则返回 ``None``。" #: ../../library/asyncio-eventloop.rst:445 msgid "Opening network connections" msgstr "打开网络连接" #: ../../library/asyncio-eventloop.rst:457 msgid "" "Open a streaming transport connection to a given address specified by *host*" " and *port*." msgstr "打开一个流式传输连接,连接到由 *host* 和 *port* 指定的地址。" #: ../../library/asyncio-eventloop.rst:460 msgid "" "The socket family can be either :py:const:`~socket.AF_INET` or " ":py:const:`~socket.AF_INET6` depending on *host* (or the *family* argument, " "if provided)." msgstr "" "套接字族可以是 :py:const:`~socket.AF_INET` 或 :py:const:`~socket.AF_INET6`,具体取决于 " "*host* (或 *family* 参数,如果有提供的话)。" #: ../../library/asyncio-eventloop.rst:464 msgid "The socket type will be :py:const:`~socket.SOCK_STREAM`." msgstr "套接字类型将为 :py:const:`~socket.SOCK_STREAM`。" #: ../../library/asyncio-eventloop.rst:466 #: ../../library/asyncio-eventloop.rst:1274 #: ../../library/asyncio-eventloop.rst:1293 msgid "" "*protocol_factory* must be a callable returning an :ref:`asyncio protocol " "` implementation." msgstr "" "*protocol_factory* 必须为一个返回 :ref:`asyncio 协议 ` 实现的可调用对象。" #: ../../library/asyncio-eventloop.rst:469 msgid "" "This method will try to establish the connection in the background. When " "successful, it returns a ``(transport, protocol)`` pair." msgstr "这个方法会尝试在后台创建连接。当创建成功,返回 ``(transport, protocol)`` 组合。" #: ../../library/asyncio-eventloop.rst:472 msgid "The chronological synopsis of the underlying operation is as follows:" msgstr "底层操作的大致的执行顺序是这样的:" #: ../../library/asyncio-eventloop.rst:474 msgid "" "The connection is established and a :ref:`transport ` is " "created for it." msgstr "创建连接并为其创建一个 :ref:`传输 `。" #: ../../library/asyncio-eventloop.rst:477 msgid "" "*protocol_factory* is called without arguments and is expected to return a " ":ref:`protocol ` instance." msgstr "不带参数地调用 *protocol_factory* 并预期返回一个 :ref:`协议 ` 实例。" #: ../../library/asyncio-eventloop.rst:480 msgid "" "The protocol instance is coupled with the transport by calling its " ":meth:`~BaseProtocol.connection_made` method." msgstr "协议实例通过调用其 :meth:`~BaseProtocol.connection_made` 方法与传输进行配对。" #: ../../library/asyncio-eventloop.rst:483 msgid "A ``(transport, protocol)`` tuple is returned on success." msgstr "成功时返回一个 ``(transport, protocol)`` 元组。" #: ../../library/asyncio-eventloop.rst:485 msgid "" "The created transport is an implementation-dependent bidirectional stream." msgstr "创建的传输是一个具体实现相关的双向流。" #: ../../library/asyncio-eventloop.rst:488 #: ../../library/asyncio-eventloop.rst:621 msgid "Other arguments:" msgstr "其他参数:" #: ../../library/asyncio-eventloop.rst:490 msgid "" "*ssl*: if given and not false, a SSL/TLS transport is created (by default a " "plain TCP transport is created). If *ssl* is a :class:`ssl.SSLContext` " "object, this context is used to create the transport; if *ssl* is " ":const:`True`, a default context returned from " ":func:`ssl.create_default_context` is used." msgstr "" "*ssl*: 如果给定该参数且不为假值,则会创建一个 SSL/TLS 传输(默认创建一个纯 TCP 传输)。如果 *ssl* 是一个 " ":class:`ssl.SSLContext` 对象,则会使用此上下文来创建传输对象;如果 *ssl* 为 :const:`True`,则会使用从 " ":func:`ssl.create_default_context` 返回的默认上下文。" #: ../../library/asyncio-eventloop.rst:496 msgid ":ref:`SSL/TLS security considerations `" msgstr ":ref:`SSL/TLS 安全考量 `" #: ../../library/asyncio-eventloop.rst:498 msgid "" "*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 " "``None``. 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)." msgstr "" "*server_hostname* 设置或覆盖目标服务器的证书将要匹配的主机名。应当只在 *ssl* 不为 ``None`` 时传入。 默认情况下会使用" " *host* 参数的值。如果 *host* 为空那就没有默认值,你必须为 *server_hostname* 传入一个值。如果 " "*server_hostname* 为空字符串,则主机名匹配会被禁用(这是一个严重的安全风险,使得潜在的中间人攻击成为可能)。" #: ../../library/asyncio-eventloop.rst:506 msgid "" "*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 :mod:`socket` module " "constants." msgstr "" "*family*, *proto*, *flags* 是可选的地址族、协议和标志,它们会被传递给 getaddrinfo() 来对 *host* " "进行解析。如果要指定的话,这些都应该是来自于 :mod:`socket` 模块的对应常量。" #: ../../library/asyncio-eventloop.rst:511 msgid "" "*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 :rfc:`8305`. A sensible default value recommended by " "the RFC is ``0.25`` (250 milliseconds)." msgstr "" "如果给出 *happy_eyeballs_delay*,它将为此连接启用 Happy Eyeballs。 " "该函数应当为一个表示在开始下一个并行尝试之前要等待连接尝试完成的秒数的浮点数。这也就是在 :rfc:`8305` 中定义的 \"连接尝试延迟\"。该 " "RFC 所推荐的合理默认值为 ``0.25`` (250 毫秒)。" #: ../../library/asyncio-eventloop.rst:519 msgid "" "*interleave* controls address reordering when a host name resolves to " "multiple IP addresses. If ``0`` or unspecified, no reordering is done, and " "addresses are tried in the order returned by :meth:`getaddrinfo`. 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 :rfc:`8305`. The default is ``0`` if " "*happy_eyeballs_delay* is not specified, and ``1`` if it is." msgstr "" "*interleave* 控制当主机名解析为多个 IP 地址时的地址重排序。如果该参数为 ``0`` 或未指定,则不会进行重排序,这些地址会按 " ":meth:`getaddrinfo` 所返回的顺序进行尝试。如果指定了一个正整数,这些地址会按地址族交错排列,而指定的整数会被解读为 " ":rfc:`8305` 所定义的 \"首个地址族计数\"。如果 *happy_eyeballs_delay* 未指定则默认值为 ``0``,否则为 " "``1``。" #: ../../library/asyncio-eventloop.rst:528 msgid "" "*sock*, if given, should be an existing, already connected " ":class:`socket.socket` 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." msgstr "" "如果给出 *sock*,它应当是一个已存在、已连接并将被传输所使用的 :class:`socket.socket` 对象。如果给出了 *sock*,则 " "*host*, *port*, *family*, *proto*, *flags*, *happy_eyeballs_delay*, " "*interleave* 和 *local_addr* 都不应当被指定。" #: ../../library/asyncio-eventloop.rst:536 #: ../../library/asyncio-eventloop.rst:658 #: ../../library/asyncio-eventloop.rst:906 msgid "" "The *sock* argument transfers ownership of the socket to the transport " "created. To close the socket, call the transport's " ":meth:`~asyncio.BaseTransport.close` method." msgstr "" "*sock* 参数可将套接字的所有权转给所创建的传输。要关闭该套接字,请调用传输的 " ":meth:`~asyncio.BaseTransport.close` 方法。" #: ../../library/asyncio-eventloop.rst:540 msgid "" "*local_addr*, if given, is a ``(local_host, local_port)`` tuple used to bind" " the socket locally. The *local_host* and *local_port* are looked up using " "``getaddrinfo()``, similarly to *host* and *port*." msgstr "" "如果给出 *local_addr*,它应当是一个用来在本地绑定套接字的 ``(local_host, local_port)`` 元组。 " "*local_host* 和 *local_port* 会使用 ``getaddrinfo()`` 来查找,这与 *host* 和 *port* 类似。" #: ../../library/asyncio-eventloop.rst:544 #: ../../library/asyncio-eventloop.rst:1002 msgid "" "*ssl_handshake_timeout* is (for a TLS connection) the time in seconds to " "wait for the TLS handshake to complete before aborting the connection. " "``60.0`` seconds if ``None`` (default)." msgstr "" "*ssl_handshake_timeout* 是(用于 TLS 连接的)在放弃连接之前要等待 TLS 握手完成的秒数。如果参数为 ``None`` " "则使用 (默认的) ``60.0``。" #: ../../library/asyncio-eventloop.rst:548 #: ../../library/asyncio-eventloop.rst:813 #: ../../library/asyncio-eventloop.rst:917 #: ../../library/asyncio-eventloop.rst:1006 msgid "" "*ssl_shutdown_timeout* is the time in seconds to wait for the SSL shutdown " "to complete before aborting the connection. ``30.0`` seconds if ``None`` " "(default)." msgstr "" "*ssl_shutdown_timeout* 是在放弃连接之前要等待 SSL 关闭完成的秒数。如为 ``None`` (默认值) 则使用 " "``30.0``。" #: ../../library/asyncio-eventloop.rst:552 msgid "" "*all_errors* determines what exceptions are raised when a connection cannot " "be created. By default, only a single ``Exception`` is raised: the first " "exception if there is only one or all errors have same message, or a single " "``OSError`` with the error messages combined. When ``all_errors`` is " "``True``, an ``ExceptionGroup`` will be raised containing all exceptions " "(even if there is only one)." msgstr "" "*all_errors* 确定当无法创建连接时要引发何种异常。在默认情况下,只有一个 ``Exception`` " "会被引发:即只有一个异常或所有错误的消息相同,或者是合并了多个错误消息的单个 ``OSError``。当 ``all_errors`` 为 " "``True`` 时,将引发一个包含所有异常的 ``ExceptionGroup`` (即使只有一个异常)。" #: ../../library/asyncio-eventloop.rst:562 #: ../../library/asyncio-eventloop.rst:825 msgid "Added support for SSL/TLS in :class:`ProactorEventLoop`." msgstr ":class:`ProactorEventLoop` 类中添加 SSL/TLS 支持。" #: ../../library/asyncio-eventloop.rst:566 msgid "" "The socket option :ref:`socket.TCP_NODELAY ` is set " "by default for all TCP connections." msgstr "" "套接字选项 :ref:`socket.TCP_NODELAY ` 默认将为所有 TCP 连接设置。" #: ../../library/asyncio-eventloop.rst:571 #: ../../library/asyncio-eventloop.rst:927 msgid "Added the *ssl_handshake_timeout* parameter." msgstr "添加了 *ssl_handshake_timeout* 参数。" #: ../../library/asyncio-eventloop.rst:575 msgid "Added the *happy_eyeballs_delay* and *interleave* parameters." msgstr "增加了 *happy_eyeballs_delay* 和 *interleave* 形参。" #: ../../library/asyncio-eventloop.rst:577 msgid "" "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." msgstr "" "Happy Eyeballs 算法:成功使用双栈主机。当服务器的 IPv4 路径和协议工作正常,但服务器的 IPv6 " "路径和协议工作不正常时,双线客户端应用程序相比仅有 IPv4 的客户端会感受到明显的连接延迟。这是不可接受的因为它会导致双栈客户端糟糕的用户体验。 " "这篇文档指明了减少这种用户可见延迟的算法要求并提供了具体的算法。" #: ../../library/asyncio-eventloop.rst:586 msgid "For more information: https://datatracker.ietf.org/doc/html/rfc6555" msgstr "详情参见:https://datatracker.ietf.org/doc/html/rfc6555" #: ../../library/asyncio-eventloop.rst:590 #: ../../library/asyncio-eventloop.rst:722 #: ../../library/asyncio-eventloop.rst:839 #: ../../library/asyncio-eventloop.rst:879 #: ../../library/asyncio-eventloop.rst:931 #: ../../library/asyncio-eventloop.rst:1014 msgid "Added the *ssl_shutdown_timeout* parameter." msgstr "添加了 *ssl_shutdown_timeout* 形参。" #: ../../library/asyncio-eventloop.rst:592 msgid "*all_errors* was added." msgstr "添加了 *all_errors*。" #: ../../library/asyncio-eventloop.rst:597 msgid "" "The :func:`open_connection` function is a high-level alternative API. It " "returns a pair of (:class:`StreamReader`, :class:`StreamWriter`) that can be" " used directly in async/await code." msgstr "" ":func:`open_connection` 函数是一个高层级的替代 API。它返回一对 (:class:`StreamReader`, " ":class:`StreamWriter`),可在 async/await 代码中直接使用。" #: ../../library/asyncio-eventloop.rst:608 msgid "Create a datagram connection." msgstr "创建一个数据报连接。" #: ../../library/asyncio-eventloop.rst:610 msgid "" "The socket family can be either :py:const:`~socket.AF_INET`, " ":py:const:`~socket.AF_INET6`, or :py:const:`~socket.AF_UNIX`, depending on " "*host* (or the *family* argument, if provided)." msgstr "" "套接字族可以是 :py:const:`~socket.AF_INET`, :py:const:`~socket.AF_INET6` 或 " ":py:const:`~socket.AF_UNIX`,具体取决于 *host* (或 *family* 参数,如果有提供的话)。" #: ../../library/asyncio-eventloop.rst:614 msgid "The socket type will be :py:const:`~socket.SOCK_DGRAM`." msgstr "套接字类型将为 :py:const:`~socket.SOCK_DGRAM`。" #: ../../library/asyncio-eventloop.rst:616 #: ../../library/asyncio-eventloop.rst:749 #: ../../library/asyncio-eventloop.rst:898 msgid "" "*protocol_factory* must be a callable returning a :ref:`protocol ` implementation." msgstr "*protocol_factory* 必须为一个返回 :ref:`协议 ` 实现的可调用对象。" #: ../../library/asyncio-eventloop.rst:619 #: ../../library/asyncio-eventloop.rst:704 msgid "A tuple of ``(transport, protocol)`` is returned on success." msgstr "成功时返回一个 ``(transport, protocol)`` 元组。" #: ../../library/asyncio-eventloop.rst:623 msgid "" "*local_addr*, if given, is a ``(local_host, local_port)`` tuple used to bind" " the socket locally. The *local_host* and *local_port* are looked up using " ":meth:`getaddrinfo`." msgstr "" "如果给出 *local_addr*,它应当是一个用来在本地绑定套接字的 ``(local_host, local_port)`` 元组。 " "*local_host* 和 *local_port* 是使用 :meth:`getaddrinfo` 来查找的。" #: ../../library/asyncio-eventloop.rst:629 msgid "" "On Windows, when using the proactor event loop with ``local_addr=None``, an " ":exc:`OSError` with :attr:`!errno.WSAEINVAL` will be raised when running it." msgstr "" "在 Windows 系统上,当使用 proactor 事件循环并且设置 ``local_addr=None`` 时,运行过程中将会引发一个带有 " ":attr:`!errno.WSAEINVAL` 错误码的 :exc:`OSError` 异常。" #: ../../library/asyncio-eventloop.rst:633 msgid "" "*remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used to " "connect the socket to a remote address. The *remote_host* and *remote_port*" " are looked up using :meth:`getaddrinfo`." msgstr "" "*remote_addr*,如果指定的话,就是一个 ``(remote_host, remote_port)`` " "元组,用于同一个远程地址连接。*remote_host* 和 *remote_port* 是使用 :meth:`getaddrinfo` 来查找的。" #: ../../library/asyncio-eventloop.rst:637 msgid "" "*family*, *proto*, *flags* are the optional address family, protocol and " "flags to be passed through to :meth:`getaddrinfo` for *host* resolution. If " "given, these should all be integers from the corresponding :mod:`socket` " "module constants." msgstr "" "*family*, *proto*, *flags* 是可选的地址族,协议和标志,其会被传递给 :meth:`getaddrinfo` 来完成 " "*host* 的解析。如果要指定的话,这些都应该是来自于 :mod:`socket` 模块的对应常量。" #: ../../library/asyncio-eventloop.rst:642 msgid "" "*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 :ref:`socket.SO_REUSEPORT ` constant " "is not defined then this capability is unsupported." msgstr "" "*reuse_port* 告知内核允许此端点绑定到其他现有端点所绑定的相同端口上,只要它们在创建时都设置了这个旗标。这个选项在 Windows 和某些 " "Unix 上将不受支持。如果 :ref:`socket.SO_REUSEPORT ` " "常量未被定义那么该功能就是不受支持的。" #: ../../library/asyncio-eventloop.rst:648 msgid "" "*allow_broadcast* tells the kernel to allow this endpoint to send messages " "to the broadcast address." msgstr "*allow_broadcast* 告知内核允许此端点向广播地址发送消息。" #: ../../library/asyncio-eventloop.rst:651 msgid "" "*sock* can optionally be specified in order to use a preexisting, already " "connected, :class:`socket.socket` object to be used by the transport. If " "specified, *local_addr* and *remote_addr* should be omitted (must be " ":const:`None`)." msgstr "" "*sock* 可选择通过指定此值用于使用一个预先存在的,已经处于连接状态的 :class:`socket.socket` " "对象,并将其提供给此传输对象使用。如果指定了这个值, *local_addr* 和 *remote_addr* 就应该被忽略 (必须为 " ":const:`None`)." #: ../../library/asyncio-eventloop.rst:662 msgid "" "See :ref:`UDP echo client protocol ` and " ":ref:`UDP echo server protocol ` examples." msgstr "" "参见 :ref:`UDP echo 客户端协议 ` 和 :ref:`UDP " "echo 服务端协议 ` 的例子。" #: ../../library/asyncio-eventloop.rst:665 msgid "" "The *family*, *proto*, *flags*, *reuse_address*, *reuse_port*, " "*allow_broadcast*, and *sock* parameters were added." msgstr "" "添加了 *family*, *proto*, *flags*, *reuse_address*, *reuse_port*, " "*allow_broadcast* 和 *sock* 等形参。" #: ../../library/asyncio-eventloop.rst:669 msgid "Added support for Windows." msgstr "添加 Windows 的支持。" #: ../../library/asyncio-eventloop.rst:672 msgid "" "The *reuse_address* parameter is no longer supported, as using " ":ref:`socket.SO_REUSEADDR ` poses a significant " "security concern for UDP. Explicitly passing ``reuse_address=True`` will " "raise an exception." msgstr "" "*reuse_address* 形参已不再受支持,因为使用 :ref:`socket.SO_REUSEADDR ` 对于 UDP 会造成显著的安全问题。显式地传入 ``reuse_address=True`` 将引发异常。" #: ../../library/asyncio-eventloop.rst:678 msgid "" "When multiple processes with differing UIDs assign sockets to an identical " "UDP socket address with ``SO_REUSEADDR``, incoming packets can become " "randomly distributed among the sockets." msgstr "" "当具有不同 UID 的多个进程将套接字赋给具有 ``SO_REUSEADDR`` 的相同 UDP 套接字地址时,传入的数据包可能会在套接字间随机分配。" #: ../../library/asyncio-eventloop.rst:682 msgid "" "For supported platforms, *reuse_port* can be used as a replacement for " "similar functionality. With *reuse_port*, :ref:`socket.SO_REUSEPORT ` is used instead, which specifically prevents processes with" " differing UIDs from assigning sockets to the same socket address." msgstr "" "对于受支持的平台,可以使用 *reuse_port* 作为类似功能的替代。通过 *reuse_port*,将会改用 " ":ref:`socket.SO_REUSEPORT `,它能防止具有不同 UID " "的进程将套接字赋给相同的套接字地址。" #: ../../library/asyncio-eventloop.rst:689 msgid "" "The *reuse_address* parameter, disabled since Python 3.8.1, 3.7.6 and " "3.6.10, has been entirely removed." msgstr "自 Python 3.8.1, 3.7.6 和 3.6.10 起被禁用的 *reuse_address* 形参现已被完全移除。" #: ../../library/asyncio-eventloop.rst:699 msgid "Create a Unix connection." msgstr "创建 Unix 连接。" #: ../../library/asyncio-eventloop.rst:701 msgid "" "The socket family will be :py:const:`~socket.AF_UNIX`; socket type will be " ":py:const:`~socket.SOCK_STREAM`." msgstr "" "套接字族将为 :py:const:`~socket.AF_UNIX`;套接字类型将为 :py:const:`~socket.SOCK_STREAM`。" #: ../../library/asyncio-eventloop.rst:706 msgid "" "*path* is the name of a Unix domain socket and is required, unless a *sock* " "parameter is specified. Abstract Unix sockets, :class:`str`, " ":class:`bytes`, and :class:`~pathlib.Path` paths are supported." msgstr "" "*path* 是所要求的 Unix 域套接字的名字,除非指定了 *sock* 形参。抽象的 Unix 套接字,:class:`str`, " ":class:`bytes` 和 :class:`~pathlib.Path` 路径都是受支持的。" #: ../../library/asyncio-eventloop.rst:711 msgid "" "See the documentation of the :meth:`loop.create_connection` method for " "information about arguments to this method." msgstr "请查看 :meth:`loop.create_connection` 方法的文档了解有关此方法的参数的信息。" #: ../../library/asyncio-eventloop.rst:714 #: ../../library/asyncio-eventloop.rst:870 #: ../../library/asyncio-eventloop.rst:1376 #: ../../library/asyncio-eventloop.rst:1929 #: ../../library/asyncio-eventloop.rst:1936 msgid "Availability" msgstr "Availability" #: ../../library/asyncio-eventloop.rst:716 msgid "" "Added the *ssl_handshake_timeout* parameter. The *path* parameter can now be" " a :term:`path-like object`." msgstr "" "增加了 *ssl_handshake_timeout* 参数。现在 *path* 参数可以是一个 :term:`path-like object`。" #: ../../library/asyncio-eventloop.rst:726 msgid "Creating network servers" msgstr "创建网络服务" #: ../../library/asyncio-eventloop.rst:742 msgid "" "Create a TCP server (socket type :const:`~socket.SOCK_STREAM`) listening on " "*port* of the *host* address." msgstr "" "创建一个 TCP 服务器 (套接字类型 :const:`~socket.SOCK_STREAM`) 在 *host* 地址的 *port* 上进行监听。" #: ../../library/asyncio-eventloop.rst:745 msgid "Returns a :class:`Server` object." msgstr "返回一个 :class:`Server` 对象。" #: ../../library/asyncio-eventloop.rst:747 msgid "Arguments:" msgstr "参数:" #: ../../library/asyncio-eventloop.rst:752 msgid "" "The *host* parameter can be set to several types which determine where the " "server would be listening:" msgstr "*host* 形参可被设为几种类型,它确定了服务器所应监听的位置:" #: ../../library/asyncio-eventloop.rst:755 msgid "" "If *host* is a string, the TCP server is bound to a single network interface" " specified by *host*." msgstr "如果 *host* 是一个字符串,则 TCP 服务器会被绑定到 *host* 所指明的单一网络接口。" #: ../../library/asyncio-eventloop.rst:758 msgid "" "If *host* is a sequence of strings, the TCP server is bound to all network " "interfaces specified by the sequence." msgstr "如果 *host* 是一个字符串序列,则 TCP 服务器会被绑定到序列所指明的所有网络接口。" #: ../../library/asyncio-eventloop.rst:761 msgid "" "If *host* is an empty string or ``None``, all interfaces are assumed and a " "list of multiple sockets will be returned (most likely one for IPv4 and " "another one for IPv6)." msgstr "" "如果 *host* 是一个空字符串或 ``None``,则会应用所有接口并将返回包含多个套接字的列表(通常是一个 IPv4 的加一个 IPv6 的)。" #: ../../library/asyncio-eventloop.rst:765 msgid "" "The *port* parameter can be set to specify which port the server should " "listen on. If ``0`` or ``None`` (the default), a random unused port will be " "selected (note that if *host* resolves to multiple network interfaces, a " "different random port will be selected for each interface)." msgstr "" "可以设置 *port* 参数来指定服务器应该监听哪个端口。 如果为 ``0`` 或者 ``None`` " "(默认值),将选择一个随机的未使用的端口(注意,如果 *host* 解析到多个网络接口,将为每个接口选择一个不同的随机端口)。" #: ../../library/asyncio-eventloop.rst:770 msgid "" "*family* can be set to either :const:`socket.AF_INET` or " ":const:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not " "set, the *family* will be determined from host name (defaults to " ":const:`~socket.AF_UNSPEC`)." msgstr "" "*family* 可被设为 :const:`socket.AF_INET` 或 :const:`~socket.AF_INET6` 以强制此套接字使用 " "IPv4 或 IPv6。如果未设定,则 *family* 将通过主机名来确定 (默认为 :const:`~socket.AF_UNSPEC`)。" #: ../../library/asyncio-eventloop.rst:775 msgid "*flags* is a bitmask for :meth:`getaddrinfo`." msgstr "*flags* 是用于 :meth:`getaddrinfo` 的位掩码。" #: ../../library/asyncio-eventloop.rst:777 msgid "" "*sock* can optionally be specified in order to use a preexisting socket " "object. If specified, *host* and *port* must not be specified." msgstr "可以选择指定 *sock* 以便使用预先存在的套接字对象。如果指定了此参数,则不可再指定 *host* 和 *port*。" #: ../../library/asyncio-eventloop.rst:782 msgid "" "The *sock* argument transfers ownership of the socket to the server created." " To close the socket, call the server's :meth:`~asyncio.Server.close` " "method." msgstr "" "*sock* 参数可将套接字的所有权转给所创建的服务器。要关闭该套接字,请调用服务器的 :meth:`~asyncio.Server.close` " "方法。" #: ../../library/asyncio-eventloop.rst:786 msgid "" "*backlog* is the maximum number of queued connections passed to " ":meth:`~socket.socket.listen` (defaults to 100)." msgstr "*backlog* 是传递给 :meth:`~socket.socket.listen` 的最大排队连接的数量(默认为 100)。" #: ../../library/asyncio-eventloop.rst:789 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` instance to enable TLS over " "the accepted connections." msgstr "*ssl* 可被设置为一个 :class:`~ssl.SSLContext` 实例以在所接受的连接上启用 TLS。" #: ../../library/asyncio-eventloop.rst:792 msgid "" "*reuse_address* tells the kernel to reuse a local socket in ``TIME_WAIT`` " "state, without waiting for its natural timeout to expire. If not specified " "will automatically be set to ``True`` on Unix." msgstr "" "*reuse_address* 告知内核要重用一个处于 ``TIME_WAIT`` 状态的本地套接字,而不是等待其自然超时失效。如果未指定此参数则在 " "Unix 上将自动设置为 ``True``。" #: ../../library/asyncio-eventloop.rst:797 msgid "" "*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." msgstr "" "*reuse_port* 告知内核,只要在创建的时候都设置了这个标志,就允许此端点绑定到其它端点列表所绑定的同样的端口上。这个选项在 Windows " "上是不支持的。" #: ../../library/asyncio-eventloop.rst:802 msgid "" "*keep_alive* set to ``True`` keeps connections active by enabling the " "periodic transmission of messages." msgstr "*keep_alive* 设为 ``True`` 将通过启用定期的消息传输来使连接保持活动状态。" #: ../../library/asyncio-eventloop.rst:807 msgid "Added the *keep_alive* parameter." msgstr "增加了 *keep_alive* 形参。" #: ../../library/asyncio-eventloop.rst:809 msgid "" "*ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait " "for the TLS handshake to complete before aborting the connection. ``60.0`` " "seconds if ``None`` (default)." msgstr "" "*ssl_handshake_timeout* 是(用于 TLS 服务器的)在放弃连接之前要等待 TLS 握手完成的秒数。 如果为 ``None`` " "(默认值) 则等于 ``60.0`` 秒。" #: ../../library/asyncio-eventloop.rst:817 msgid "" "*start_serving* set to ``True`` (the default) causes the created server to " "start accepting connections immediately. When set to ``False``, the user " "should await on :meth:`Server.start_serving` or :meth:`Server.serve_forever`" " to make the server to start accepting connections." msgstr "" "*start_serving* 设置成 ``True`` (默认值) 会导致创建服务器并立即开始接受连接。 设置成 ``False``,用户需要等待 " ":meth:`Server.start_serving` 或者 :meth:`Server.serve_forever` 以使服务器开始接受连接。" #: ../../library/asyncio-eventloop.rst:829 msgid "The *host* parameter can be a sequence of strings." msgstr "*host* 形参可以是一个字符串的序列。" #: ../../library/asyncio-eventloop.rst:833 msgid "" "Added *ssl_handshake_timeout* and *start_serving* parameters. The socket " "option :ref:`socket.TCP_NODELAY ` is set by default " "for all TCP connections." msgstr "" "增加了 *ssl_handshake_timeout* 和 *start_serving* 形参。套接字选项 " ":ref:`socket.TCP_NODELAY ` 会默认为所有 TCP 连接设置。" #: ../../library/asyncio-eventloop.rst:843 msgid "" "The :func:`start_server` function is a higher-level alternative API that " "returns a pair of :class:`StreamReader` and :class:`StreamWriter` that can " "be used in an async/await code." msgstr "" ":func:`start_server` 函数是一个高层级的替代 API,它返回一对 :class:`StreamReader` 和 " ":class:`StreamWriter`,可在 async/await 代码中使用。" #: ../../library/asyncio-eventloop.rst:855 msgid "" "Similar to :meth:`loop.create_server` but works with the " ":py:const:`~socket.AF_UNIX` socket family." msgstr "" "与 :meth:`loop.create_server` 类似但是专用于 :py:const:`~socket.AF_UNIX` 套接字族。" #: ../../library/asyncio-eventloop.rst:858 msgid "" "*path* is the name of a Unix domain socket, and is required, unless a *sock*" " argument is provided. Abstract Unix sockets, :class:`str`, :class:`bytes`," " and :class:`~pathlib.Path` paths are supported." msgstr "" "*path* 是必要的 Unix 域套接字名称,除非提供了 *sock* 参数。抽象的 Unix 套接字,:class:`str`, " ":class:`bytes` 和 :class:`~pathlib.Path` 路径都是受支持的。" #: ../../library/asyncio-eventloop.rst:863 msgid "" "If *cleanup_socket* is true then the Unix socket will automatically be " "removed from the filesystem when the server is closed, unless the socket has" " been replaced after the server has been created." msgstr "" "如果 *cleanup_socket* 为真值那么当服务器关闭时 Unix 套接字将自动从文件系统中被移除,除非套接字在服务器创建之后被替换。" #: ../../library/asyncio-eventloop.rst:867 msgid "" "See the documentation of the :meth:`loop.create_server` method for " "information about arguments to this method." msgstr "请查看 :meth:`loop.create_server` 方法的文档了解有关此方法的参数的信息。" #: ../../library/asyncio-eventloop.rst:874 msgid "" "Added the *ssl_handshake_timeout* and *start_serving* parameters. The *path*" " parameter can now be a :class:`~pathlib.Path` object." msgstr "" "增加了 *ssl_handshake_timeout* 和 *start_serving* 参数。现在 *path* 参数可以是一个 " ":class:`~pathlib.Path` 对象。" #: ../../library/asyncio-eventloop.rst:883 msgid "Added the *cleanup_socket* parameter." msgstr "增加了 *cleanup_socket* 形参。" #: ../../library/asyncio-eventloop.rst:891 msgid "Wrap an already accepted connection into a transport/protocol pair." msgstr "将已被接受的连接包装成一个传输/协议对。" #: ../../library/asyncio-eventloop.rst:893 msgid "" "This method can be used by servers that accept connections outside of " "asyncio but that use asyncio to handle them." msgstr "此方法可被服务器用来接受 asyncio 以外的连接,但是使用 asyncio 来处理它们。" #: ../../library/asyncio-eventloop.rst:896 #: ../../library/asyncio-eventloop.rst:988 msgid "Parameters:" msgstr "参数:" #: ../../library/asyncio-eventloop.rst:901 msgid "" "*sock* is a preexisting socket object returned from :meth:`socket.accept " "`." msgstr "" "*sock* 是一个预先存在的套接字对象,它是由 :meth:`socket.accept ` 返回的。" #: ../../library/asyncio-eventloop.rst:910 msgid "" "*ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the " "accepted connections." msgstr "*ssl* 可被设置为一个 :class:`~ssl.SSLContext` 以在接受的连接上启用 SSL。" #: ../../library/asyncio-eventloop.rst:913 msgid "" "*ssl_handshake_timeout* is (for an SSL connection) the time in seconds to " "wait for the SSL handshake to complete before aborting the connection. " "``60.0`` seconds if ``None`` (default)." msgstr "" "*ssl_handshake_timeout* 是 (为一个 SSL 连接) 在中止连接前,等待 SSL 握手完成的时间【单位秒】。如果为 " "``None`` (缺省) 则是 ``60.0`` 秒。" #: ../../library/asyncio-eventloop.rst:921 msgid "Returns a ``(transport, protocol)`` pair." msgstr "返回一个 ``(transport, protocol)`` 对。" #: ../../library/asyncio-eventloop.rst:935 msgid "Transferring files" msgstr "传输文件" #: ../../library/asyncio-eventloop.rst:941 msgid "" "Send a *file* over a *transport*. Return the total number of bytes sent." msgstr "将 *file* 通过 *transport* 发送。返回所发送的字节总数。" #: ../../library/asyncio-eventloop.rst:944 msgid "The method uses high-performance :meth:`os.sendfile` if available." msgstr "如果可用的话,该方法将使用高性能的 :meth:`os.sendfile`。" #: ../../library/asyncio-eventloop.rst:946 msgid "*file* must be a regular file object opened in binary mode." msgstr "*file* 必须是个二进制模式打开的常规文件对象。" #: ../../library/asyncio-eventloop.rst:948 #: ../../library/asyncio-eventloop.rst:1218 msgid "" "*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 :meth:`file.tell() ` can be used to " "obtain the actual number of bytes sent." msgstr "" "*offset* 指明从何处开始读取文件。如果指定了 *count*,它是要传输的字节总数而不再一直发送文件直至抵达 EOF。 " "文件位置总是会被更新,即使此方法引发了错误,并可以使用 :meth:`file.tell() ` " "来获取实际发送的字节总数。" #: ../../library/asyncio-eventloop.rst:955 msgid "" "*fallback* set to ``True`` 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)." msgstr "" "*fallback* 设为 ``True`` 会使得 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件(例如 Windows" " 或 Unix 上的 SSL 套接字)。" #: ../../library/asyncio-eventloop.rst:959 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support the " "*sendfile* syscall and *fallback* is ``False``." msgstr "" "如果系统不支持 *sendfile* 系统调用且 *fallback* 为 ``False`` 则会引发 " ":exc:`SendfileNotAvailableError`." #: ../../library/asyncio-eventloop.rst:966 msgid "TLS upgrade" msgstr "TLS 升级" #: ../../library/asyncio-eventloop.rst:974 msgid "Upgrade an existing transport-based connection to TLS." msgstr "将现有基于传输的连接升级到 TLS。" #: ../../library/asyncio-eventloop.rst:976 msgid "" "Create a TLS coder/decoder instance and insert it between the *transport* " "and the *protocol*. The coder/decoder implements both *transport*-facing " "protocol and *protocol*-facing transport." msgstr "" "创建一个 TLS 编码器/解码器实例并将其插入到 *transport* 和 *protocol* 之间。该编码器/解码器同时实现了面向 " "*transport* 的协议和面向 *protocol* 的传输。" #: ../../library/asyncio-eventloop.rst:980 msgid "" "Return the created two-interface instance. After *await*, the *protocol* " "must stop using the original *transport* and communicate with the returned " "object only because the coder caches *protocol*-side data and sporadically " "exchanges extra TLS session packets with *transport*." msgstr "" "返回已创建的双接口实例。在 *await* 之后,*protocol* 必须停止使用原始 *transport* " "并仅与所返回的对象通信,因为编码器会缓存 *protocol* 方的数据并会不定期地与 *transport* 交换额外的 TLS 会话数据包。" #: ../../library/asyncio-eventloop.rst:985 msgid "" "In some situations (e.g. when the passed transport is already closing) this " "may return ``None``." msgstr "在某些情况下(例如当传入的 transport 已经关闭)这可能返回 ``None``。" #: ../../library/asyncio-eventloop.rst:990 msgid "" "*transport* and *protocol* instances that methods like " ":meth:`~loop.create_server` and :meth:`~loop.create_connection` return." msgstr "" "由 :meth:`~loop.create_server` 和 :meth:`~loop.create_connection` 等方法所返回的 " "*transport* 和 *protocol* 实例。" #: ../../library/asyncio-eventloop.rst:994 msgid "*sslcontext*: a configured instance of :class:`~ssl.SSLContext`." msgstr "*sslcontext* :一个已经配置好的 :class:`~ssl.SSLContext` 实例。" #: ../../library/asyncio-eventloop.rst:996 msgid "" "*server_side* pass ``True`` when a server-side connection is being upgraded " "(like the one created by :meth:`~loop.create_server`)." msgstr "" "当服务端连接已升级时 (如 :meth:`~loop.create_server` 所创建的对象) *server_side* 会传入 " "``True``." #: ../../library/asyncio-eventloop.rst:999 msgid "" "*server_hostname*: sets or overrides the host name that the target server's " "certificate will be matched against." msgstr "*server_hostname* :设置或者覆盖目标服务器证书中相对应的主机名。" #: ../../library/asyncio-eventloop.rst:1019 msgid "Watching file descriptors" msgstr "监控文件描述符" #: ../../library/asyncio-eventloop.rst:1023 msgid "" "Start monitoring the *fd* file descriptor for read availability and invoke " "*callback* with the specified arguments once *fd* is available for reading." msgstr "开始监视 *fd* 文件描述符以获取读取的可用性,一旦 *fd* 可用于读取,使用指定的参数调用 *callback* 。" #: ../../library/asyncio-eventloop.rst:1027 #: ../../library/asyncio-eventloop.rst:1041 msgid "" "Any preexisting callback registered for *fd* is cancelled and replaced by " "*callback*." msgstr "任何为 *fd* 注册的预先存在的回调都会被取消并由 *callback* 代替。" #: ../../library/asyncio-eventloop.rst:1032 msgid "" "Stop monitoring the *fd* file descriptor for read availability. Returns " "``True`` if *fd* was previously being monitored for reads." msgstr "停止监视 *fd* 文件描述符的读取可用性。如果之前正在监视 *fd* 的读取则返回 ``True``。" #: ../../library/asyncio-eventloop.rst:1037 msgid "" "Start monitoring the *fd* file descriptor for write availability and invoke " "*callback* with the specified arguments *args* once *fd* is available for " "writing." msgstr "开始监视 *fd* 文件描述符的写入可用性并在 *fd* 可用于写入时唤起 *callback* 并附带指定的参数 *args*。" #: ../../library/asyncio-eventloop.rst:1044 #: ../../library/asyncio-eventloop.rst:1363 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *callback*." msgstr "" "使用 :func:`functools.partial` :ref:`传递关键字参数 ` 给 " "*callback*." #: ../../library/asyncio-eventloop.rst:1049 msgid "" "Stop monitoring the *fd* file descriptor for write availability. Returns " "``True`` if *fd* was previously being monitored for writes." msgstr "停止监视 *fd* 文件描述符的写入可用性。如果之前正在监视 *fd* 的写入则返回 ``True``。" #: ../../library/asyncio-eventloop.rst:1052 msgid "" "See also :ref:`Platform Support ` section for some" " limitations of these methods." msgstr "另请查看 :ref:`平台支持 ` 一节了解以上方法的某些限制。" #: ../../library/asyncio-eventloop.rst:1057 msgid "Working with socket objects directly" msgstr "直接使用 socket 对象" #: ../../library/asyncio-eventloop.rst:1059 msgid "" "In general, protocol implementations that use transport-based APIs such as " ":meth:`loop.create_connection` and :meth:`loop.create_server` are faster " "than implementations that work with sockets directly. However, there are " "some use cases when performance is not critical, and working with " ":class:`~socket.socket` objects directly is more convenient." msgstr "" "通常,使用基于传输的 API 的协议实现,例如 :meth:`loop.create_connection` 和 " ":meth:`loop.create_server` 比直接使用套接字的实现更快。但是,在某些应用场景下性能并不非常重要,直接使用 " ":class:`~socket.socket` 对象会更方便。" #: ../../library/asyncio-eventloop.rst:1069 msgid "" "Receive up to *nbytes* from *sock*. Asynchronous version of " ":meth:`socket.recv() `." msgstr "" "从 *sock* 接收至多 *nbytes*。 :meth:`socket.recv() ` 的异步版本。" #: ../../library/asyncio-eventloop.rst:1072 msgid "Return the received data as a bytes object." msgstr "返回接收到的数据(bytes 对象)。" #: ../../library/asyncio-eventloop.rst:1074 #: ../../library/asyncio-eventloop.rst:1089 #: ../../library/asyncio-eventloop.rst:1101 #: ../../library/asyncio-eventloop.rst:1114 #: ../../library/asyncio-eventloop.rst:1130 #: ../../library/asyncio-eventloop.rst:1146 #: ../../library/asyncio-eventloop.rst:1157 #: ../../library/asyncio-eventloop.rst:1193 #: ../../library/asyncio-eventloop.rst:1232 msgid "*sock* must be a non-blocking socket." msgstr "*sock* 必须是个非阻塞套接字。" #: ../../library/asyncio-eventloop.rst:1076 msgid "" "Even though this method was always documented as a coroutine method, " "releases before Python 3.7 returned a :class:`Future`. Since Python 3.7 this" " is an ``async def`` method." msgstr "" "虽然这个方法总是被记录为协程方法,但它在 Python 3.7 之前的发行版中会返回一个 :class:`Future`。从 Python 3.7 " "开始它则是一个 ``async def`` 方法。" #: ../../library/asyncio-eventloop.rst:1084 msgid "" "Receive data from *sock* into the *buf* buffer. Modeled after the blocking " ":meth:`socket.recv_into() ` method." msgstr "" "从 *sock* 接收数据放入 *buf* 缓冲区。模仿了阻塞型的 :meth:`socket.recv_into() " "` 方法。" #: ../../library/asyncio-eventloop.rst:1087 msgid "Return the number of bytes written to the buffer." msgstr "返回写入缓冲区的字节数。" #: ../../library/asyncio-eventloop.rst:1096 msgid "" "Receive a datagram of up to *bufsize* from *sock*. Asynchronous version of " ":meth:`socket.recvfrom() `." msgstr "" "从 *sock* 接收最大为 *bufsize* 的数据报。 :meth:`socket.recvfrom() " "` 的异步版本。" #: ../../library/asyncio-eventloop.rst:1099 msgid "Return a tuple of (received data, remote address)." msgstr "返回一个 (已接收数据,远程地址) 元组。" #: ../../library/asyncio-eventloop.rst:1108 msgid "" "Receive a datagram of up to *nbytes* from *sock* into *buf*. Asynchronous " "version of :meth:`socket.recvfrom_into() `." msgstr "" "从 *sock* 接收最大为 *nbytes* 的数据报并放入 *buf*。 :meth:`socket.recvfrom_into() " "` 的异步版本。" #: ../../library/asyncio-eventloop.rst:1112 msgid "Return a tuple of (number of bytes received, remote address)." msgstr "返回一个 (已接收字节数,远程地址) 元组。" #: ../../library/asyncio-eventloop.rst:1121 msgid "" "Send *data* to the *sock* socket. Asynchronous version of " ":meth:`socket.sendall() `." msgstr "" "将 *data* 发送到 *sock* 套接字。 :meth:`socket.sendall() ` " "的异步版本。" #: ../../library/asyncio-eventloop.rst:1124 msgid "" "This method continues to send to the socket until either all data in *data* " "has been sent or an error occurs. ``None`` 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." msgstr "" "此方法会持续发送数据到套接字直至 *data* 中的所有数据发送完毕或是有错误发生。当成功时会返回 ``None``。当发生错误时,会引发一个异常。 " "此外,没有办法能确定有多少数据或是否有数据被连接的接收方成功处理。" #: ../../library/asyncio-eventloop.rst:1132 #: ../../library/asyncio-eventloop.rst:1195 msgid "" "Even though the method was always documented as a coroutine method, before " "Python 3.7 it returned a :class:`Future`. Since Python 3.7, this is an " "``async def`` method." msgstr "" "虽然这个方法一直被标记为协程方法。但是,Python 3.7 之前,该方法返回 :class:`Future`,从 Python 3.7 " "开始,这个方法是 ``async def`` 方法。" #: ../../library/asyncio-eventloop.rst:1140 msgid "" "Send a datagram from *sock* to *address*. Asynchronous version of " ":meth:`socket.sendto() `." msgstr "" "从 *sock* 向 *address* 发送数据报。 :meth:`socket.sendto() ` " "的异步版本。" #: ../../library/asyncio-eventloop.rst:1144 msgid "Return the number of bytes sent." msgstr "返回已发送的字节数。" #: ../../library/asyncio-eventloop.rst:1153 msgid "Connect *sock* to a remote socket at *address*." msgstr "将 *sock* 连接到位于 *address* 的远程套接字。" #: ../../library/asyncio-eventloop.rst:1155 msgid "" "Asynchronous version of :meth:`socket.connect() `." msgstr ":meth:`socket.connect() ` 的异步版本。" #: ../../library/asyncio-eventloop.rst:1159 msgid "" "With :class:`SelectorEventLoop`, *address* does not need to be resolved: for" " :const:`~socket.AF_INET` and :const:`~socket.AF_INET6` sockets, " "``sock_connect`` first checks whether *address* is already resolved by " "calling :func:`socket.inet_pton`, and uses :meth:`loop.getaddrinfo` to " "resolve it if it is not." msgstr "" #: ../../library/asyncio-eventloop.rst:1165 msgid "" ":class:`ProactorEventLoop`, the default event loop on Windows, does not " "resolve *address*. The host must already be a numeric IP address; passing a" " host name raises :exc:`OSError`. Resolve the address with " ":meth:`loop.getaddrinfo` first, or use :meth:`loop.create_connection`, which" " resolves the address on every platform." msgstr "" #: ../../library/asyncio-eventloop.rst:1171 msgid "" "With :class:`SelectorEventLoop`, ``address`` no longer needs to be resolved." msgstr "" #: ../../library/asyncio-eventloop.rst:1177 msgid "" ":meth:`loop.create_connection` and :func:`asyncio.open_connection() " "`." msgstr "" ":meth:`loop.create_connection` 和 :func:`asyncio.open_connection() " "`." #: ../../library/asyncio-eventloop.rst:1184 msgid "" "Accept a connection. Modeled after the blocking :meth:`socket.accept() " "` method." msgstr "接受一个连接。模仿了阻塞型的 :meth:`socket.accept() ` 方法。" #: ../../library/asyncio-eventloop.rst:1187 msgid "" "The socket must be bound to an address and listening for connections. The " "return value is a pair ``(conn, address)`` 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." msgstr "" "此套接字必须绑定到一个地址上并且监听连接。返回值是一个 ``(conn, address)`` 对,其中 *conn* 是一个 " "*新*的套接字对象,用于在此连接上收发数据,*address* 是连接的另一端的套接字所绑定的地址。" #: ../../library/asyncio-eventloop.rst:1202 msgid ":meth:`loop.create_server` and :func:`start_server`." msgstr ":meth:`loop.create_server` 和 :func:`start_server`。" #: ../../library/asyncio-eventloop.rst:1208 msgid "" "Send a file using high-performance :mod:`os.sendfile` if possible. Return " "the total number of bytes sent." msgstr "在可能的情况下使用高性能的 :mod:`os.sendfile` 发送文件。返回所发送的字节总数。" #: ../../library/asyncio-eventloop.rst:1211 msgid "" "Asynchronous version of :meth:`socket.sendfile() `." msgstr ":meth:`socket.sendfile() ` 的异步版本。" #: ../../library/asyncio-eventloop.rst:1213 msgid "" "*sock* must be a non-blocking :const:`socket.SOCK_STREAM` " ":class:`~socket.socket`." msgstr "*sock* 必须为非阻塞型的 :const:`socket.SOCK_STREAM` :class:`~socket.socket`。" #: ../../library/asyncio-eventloop.rst:1216 msgid "*file* must be a regular file object open in binary mode." msgstr "*file* 必须是个用二进制方式打开的常规文件对象。" #: ../../library/asyncio-eventloop.rst:1225 msgid "" "*fallback*, when set to ``True``, 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)." msgstr "" "当 *fallback* 被设为 ``True`` 时,会使用 asyncio 在平台不支持 sendfile 系统调用时手动读取并发送文件(例如 " "Windows 或 Unix 上的 SSL 套接字)。" #: ../../library/asyncio-eventloop.rst:1229 msgid "" "Raise :exc:`SendfileNotAvailableError` if the system does not support " "*sendfile* syscall and *fallback* is ``False``." msgstr "" "如果系统不支持 *sendfile* 并且 *fallback* 为 ``False``,引发 " ":exc:`SendfileNotAvailableError` 异常。" #: ../../library/asyncio-eventloop.rst:1238 msgid "DNS" msgstr "DNS" #: ../../library/asyncio-eventloop.rst:1244 msgid "Asynchronous version of :meth:`socket.getaddrinfo`." msgstr "异步版的 :meth:`socket.getaddrinfo`。" #: ../../library/asyncio-eventloop.rst:1249 msgid "Asynchronous version of :meth:`socket.getnameinfo`." msgstr "异步版的 :meth:`socket.getnameinfo`。" #: ../../library/asyncio-eventloop.rst:1252 msgid "" "Both *getaddrinfo* and *getnameinfo* internally utilize their synchronous " "versions through the loop's default thread pool executor. When this executor" " is saturated, these methods may experience delays, which higher-level " "networking libraries may report as increased timeouts. To mitigate this, " "consider using a custom executor for other user tasks, or setting a default " "executor with a larger number of workers." msgstr "" "*getaddrinfo* 和 *getnameinfo* 均在内部通过循环的默认线程池执行器使用其同步版本。 " "当执行器饱和时,这些方法可能会遭遇延迟,对此高层级网络库可能报告为更多的超时。 " "为缓解此问题,可以考虑使用针对其他用户任务的自定义执行器,或者设置具有更多工作线程的默认执行器。" #: ../../library/asyncio-eventloop.rst:1259 msgid "" "Both *getaddrinfo* and *getnameinfo* methods were always documented to " "return a coroutine, but prior to Python 3.7 they were, in fact, returning " ":class:`asyncio.Future` objects. Starting with Python 3.7 both methods are " "coroutines." msgstr "" "*getaddrinfo* 和 *getnameinfo* 方法一直被标记返回一个协程,但是 Python 3.7 之前,实际返回的是 " ":class:`asyncio.Future` 对象。从 Python 3.7 开始,这两个方法是协程。" #: ../../library/asyncio-eventloop.rst:1267 msgid "Working with pipes" msgstr "使用管道" #: ../../library/asyncio-eventloop.rst:1272 msgid "Register the read end of *pipe* in the event loop." msgstr "在事件循环中注册 *pipe* 的读取端。" #: ../../library/asyncio-eventloop.rst:1277 #: ../../library/asyncio-eventloop.rst:1296 msgid "" "*pipe* is a :term:`file-like object `. See :ref:`Supported " "pipe objects ` for the objects supported as *pipe*." msgstr "" #: ../../library/asyncio-eventloop.rst:1281 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports the " ":class:`ReadTransport` interface and *protocol* is an object instantiated by" " the *protocol_factory*." msgstr "" "返回一对 ``(transport, protocol)``,其中 *transport* 支持 :class:`ReadTransport` 接口而 " "*protocol* 是由 *protocol_factory* 所实例化的对象。" #: ../../library/asyncio-eventloop.rst:1285 #: ../../library/asyncio-eventloop.rst:1304 msgid "" "With :class:`SelectorEventLoop` event loop, the *pipe* is set to non-" "blocking mode." msgstr "使用 :class:`SelectorEventLoop` 事件循环, *pipe* 被设置为非阻塞模式。" #: ../../library/asyncio-eventloop.rst:1291 msgid "Register the write end of *pipe* in the event loop." msgstr "在事件循环中注册 *pipe* 的写入端。" #: ../../library/asyncio-eventloop.rst:1300 msgid "" "Return pair ``(transport, protocol)``, where *transport* supports " ":class:`WriteTransport` interface and *protocol* is an object instantiated " "by the *protocol_factory*." msgstr "" "返回一对 ``(transport, protocol)``,其中 *transport* 支持 :class:`WriteTransport` 接口而" " *protocol* 是由 *protocol_factory* 所实例化的对象。" #: ../../library/asyncio-eventloop.rst:1310 msgid "Supported pipe objects" msgstr "" #: ../../library/asyncio-eventloop.rst:1311 msgid "" "These methods only work with objects the operating system can poll for " "readiness or perform overlapped I/O on. Regular files on disk are **not** " "supported on any platform. There is no asynchronous file I/O in asyncio; " "use :meth:`loop.run_in_executor` to read and write regular files without " "blocking the event loop." msgstr "" #: ../../library/asyncio-eventloop.rst:1317 msgid "" "On Unix, with :class:`SelectorEventLoop`, *pipe* must wrap one of the " "following:" msgstr "" #: ../../library/asyncio-eventloop.rst:1320 msgid "" "a pipe, such as an end of an :func:`os.pipe` pair or a FIFO created with " ":func:`os.mkfifo`;" msgstr "" #: ../../library/asyncio-eventloop.rst:1322 msgid "a socket;" msgstr "" #: ../../library/asyncio-eventloop.rst:1323 msgid "a character device, such as a terminal." msgstr "" #: ../../library/asyncio-eventloop.rst:1325 msgid "" "On Windows, where only :class:`ProactorEventLoop` implements these methods, " "*pipe* must wrap a handle opened for overlapped I/O (that is, created with " "the ``FILE_FLAG_OVERLAPPED`` flag), since the handle has to be associated " "with an I/O completion port. Handles that were not opened for overlapped " "I/O are rejected. In particular, the standard streams (:data:`sys.stdin`, " ":data:`sys.stdout` and :data:`sys.stderr`), console handles, and the pipes " "created by :func:`os.pipe` are **not** opened for overlapped I/O and " "therefore cannot be used with these methods." msgstr "" #: ../../library/asyncio-eventloop.rst:1336 msgid "" ":class:`SelectorEventLoop` does not support the above methods on Windows. " "Use :class:`ProactorEventLoop` instead for Windows." msgstr "" "在 Windows 中 :class:`SelectorEventLoop` 不支持上述方法。对于 Windows 请改用 " ":class:`ProactorEventLoop`." #: ../../library/asyncio-eventloop.rst:1341 msgid "" "The :meth:`loop.subprocess_exec` and :meth:`loop.subprocess_shell` methods." msgstr ":meth:`loop.subprocess_exec` 和 :meth:`loop.subprocess_shell` 方法。" #: ../../library/asyncio-eventloop.rst:1346 msgid "Unix signals" msgstr "Unix 信号" #: ../../library/asyncio-eventloop.rst:1352 msgid "" "Set *callback* as the handler for the *signum* signal, passing *args* as " "positional arguments." msgstr "" "将 *callback* 设为 *signum* 信号的处理器,并传入 *args* 作为位置参数。as positional arguments." #: ../../library/asyncio-eventloop.rst:1355 msgid "" "The callback will be invoked by *loop*, along with other queued callbacks " "and runnable coroutines of that event loop. Unlike signal handlers " "registered using :func:`signal.signal`, a callback registered with this " "function is allowed to interact with the event loop." msgstr "" "此回调将与该事件循环中其他加入队列的回调和可运行协程一起由 *loop* 唤起。不同于使用 :func:`signal.signal` " "注册的信号处理程序,使用此函数注册的回调可以与事件循环进行交互。" #: ../../library/asyncio-eventloop.rst:1360 msgid "" "Raise :exc:`ValueError` if the signal number is invalid or uncatchable. " "Raise :exc:`RuntimeError` if there is a problem setting up the handler." msgstr "" "如果信号数字非法或者不可捕获,就抛出一个 :exc:`ValueError`。如果建立处理器的过程中出现问题,会抛出一个 " ":exc:`RuntimeError`." #: ../../library/asyncio-eventloop.rst:1366 msgid "" "Like :func:`signal.signal`, this function must be invoked in the main " "thread." msgstr "和 :func:`signal.signal` 一样,这个函数只能在主线程中调用。" #: ../../library/asyncio-eventloop.rst:1371 msgid "Remove the handler for the *sig* signal." msgstr "移除 *sig* 信号的处理程序。" #: ../../library/asyncio-eventloop.rst:1373 msgid "" "Return ``True`` if the signal handler was removed, or ``False`` if no " "handler was set for the given signal." msgstr "如果信号处理程序被移除则返回 ``True``,否则如果给定信号未设置处理程序则返回 ``False``。" #: ../../library/asyncio-eventloop.rst:1380 msgid "The :mod:`signal` module." msgstr ":mod:`signal` 模块。" #: ../../library/asyncio-eventloop.rst:1384 msgid "Executing code in thread or process pools" msgstr "在线程或者进程池中执行代码。" #: ../../library/asyncio-eventloop.rst:1388 msgid "" "Arrange for *func* to be called in the specified executor passing *args* as " "positional arguments." msgstr "安排 *func* 在指定的执行器中被调用并传入 *args* 作为位置参数。as positional arguments." #: ../../library/asyncio-eventloop.rst:1391 msgid "" "The *executor* argument should be an :class:`concurrent.futures.Executor` " "instance. The default executor is used if *executor* is ``None``. The " "default executor can be set by :meth:`loop.set_default_executor`, otherwise," " a :class:`concurrent.futures.ThreadPoolExecutor` will be lazy-initialized " "and used by :func:`run_in_executor` if needed." msgstr "" "*executor* 参数应当是一个 :class:`concurrent.futures.Executor` 实例。如果 *executor* 为 " "``None`` 则使用默认执行器。默认执行器可通过 :meth:`loop.set_default_executor` " "来设置,在其他情况下,将在有需要时惰性初始化 :class:`concurrent.futures.ThreadPoolExecutor` 并由 " ":func:`run_in_executor` 来使用。" #: ../../library/asyncio-eventloop.rst:1399 msgid "" "import asyncio\n" "import concurrent.futures\n" "\n" "def blocking_io():\n" " # File operations (such as logging) can block the\n" " # event loop: run them in a thread pool.\n" " with open('/dev/urandom', 'rb') as f:\n" " return f.read(100)\n" "\n" "def cpu_bound():\n" " # CPU-bound operations will block the event loop:\n" " # in general it is preferable to run them in a\n" " # process pool.\n" " return sum(i * i for i in range(10 ** 7))\n" "\n" "async def main():\n" " loop = asyncio.get_running_loop()\n" "\n" " ## Options:\n" "\n" " # 1. Run in the default loop's executor:\n" " result = await loop.run_in_executor(\n" " None, blocking_io)\n" " print('default thread pool', result)\n" "\n" " # 2. Run in a custom thread pool:\n" " with concurrent.futures.ThreadPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, blocking_io)\n" " print('custom thread pool', result)\n" "\n" " # 3. Run in a custom process pool:\n" " with concurrent.futures.ProcessPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, cpu_bound)\n" " print('custom process pool', result)\n" "\n" " # 4. Run in a custom interpreter pool:\n" " with concurrent.futures.InterpreterPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, cpu_bound)\n" " print('custom interpreter pool', result)\n" "\n" "if __name__ == '__main__':\n" " asyncio.run(main())" msgstr "" "import asyncio\n" "import concurrent.futures\n" "\n" "def blocking_io():\n" " # 文件操作(如日志记录)会阻塞\n" " # 事件循环:在线程池中运行它们。\n" " with open('/dev/urandom', 'rb') as f:\n" " return f.read(100)\n" "\n" "def cpu_bound():\n" " # CPU 密集型操作将阻塞事件循环:\n" " # 通常,最好在进程池中运行它们。\n" " return sum(i * i for i in range(10 ** 7))\n" "\n" "async def main():\n" " loop = asyncio.get_running_loop()\n" "\n" " ## 选项:\n" "\n" " # 1. 在默认循环执行器中运行:\n" " result = await loop.run_in_executor(\n" " None, blocking_io)\n" " print('default thread pool', result)\n" "\n" " # 2. 在自定义线程池中运行:\n" " with concurrent.futures.ThreadPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, blocking_io)\n" " print('custom thread pool', result)\n" "\n" " # 3. 在自定义进程池中运行:\n" " with concurrent.futures.ProcessPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, cpu_bound)\n" " print('custom process pool', result)\n" "\n" " # 4. 在自定义解释器池中运行:\n" " with concurrent.futures.InterpreterPoolExecutor() as pool:\n" " result = await loop.run_in_executor(\n" " pool, cpu_bound)\n" " print('custom interpreter pool', result)\n" "\n" "if __name__ == '__main__':\n" " asyncio.run(main())" #: ../../library/asyncio-eventloop.rst:1445 msgid "" "Note that the entry point guard (``if __name__ == '__main__'``) is required " "for option 3 due to the peculiarities of :mod:`multiprocessing`, which is " "used by :class:`~concurrent.futures.ProcessPoolExecutor`. See :ref:`Safe " "importing of main module `." msgstr "" "请注意需要为选项 3 设置入口点保护 (``if __name__ == '__main__'``),这是由于 " ":mod:`multiprocessing` 的特殊性,它将由 " ":class:`~concurrent.futures.ProcessPoolExecutor` 来使用。参见 :ref:`主模块的安全导入 " "`." #: ../../library/asyncio-eventloop.rst:1450 msgid "This method returns a :class:`asyncio.Future` object." msgstr "这个方法返回一个 :class:`asyncio.Future` 对象。" #: ../../library/asyncio-eventloop.rst:1452 msgid "" "Use :func:`functools.partial` :ref:`to pass keyword arguments ` to *func*." msgstr "" "使用 :func:`functools.partial` :ref:`传递关键字参数 ` 给 " "*func*." #: ../../library/asyncio-eventloop.rst:1455 msgid "" ":meth:`loop.run_in_executor` no longer configures the ``max_workers`` of the" " thread pool executor it creates, instead leaving it up to the thread pool " "executor (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the " "default." msgstr "" ":meth:`loop.run_in_executor` 不会再配置它所创建的线程池执行器的 ``max_workers``,而是将其留给线程池执行器 " "(:class:`~concurrent.futures.ThreadPoolExecutor`) 来设置默认值。" #: ../../library/asyncio-eventloop.rst:1464 msgid "" "Set *executor* as the default executor used by :meth:`run_in_executor`. " "*executor* must be an instance of " ":class:`~concurrent.futures.ThreadPoolExecutor`, which includes " ":class:`~concurrent.futures.InterpreterPoolExecutor`." msgstr "" "将 *executor* 设为 :meth:`run_in_executor` 所使用的默认执行器。 *executor* 必须是 " ":class:`~concurrent.futures.ThreadPoolExecutor` (其中包括 " ":class:`~concurrent.futures.InterpreterPoolExecutor`) 的实例。" #: ../../library/asyncio-eventloop.rst:1469 msgid "" "*executor* must be an instance of " ":class:`~concurrent.futures.ThreadPoolExecutor`." msgstr "*executor* 必须是 :class:`~concurrent.futures.ThreadPoolExecutor` 的实例。" #: ../../library/asyncio-eventloop.rst:1475 msgid "Error handling API" msgstr "错误处理 API" #: ../../library/asyncio-eventloop.rst:1477 msgid "Allows customizing how exceptions are handled in the event loop." msgstr "允许自定义事件循环中如何去处理异常。" #: ../../library/asyncio-eventloop.rst:1481 msgid "Set *handler* as the new event loop exception handler." msgstr "将 *handler* 设置为新的事件循环异常处理器。" #: ../../library/asyncio-eventloop.rst:1483 msgid "" "If *handler* is ``None``, the default exception handler will be set. " "Otherwise, *handler* must be a callable with the signature matching ``(loop," " context)``, where ``loop`` is a reference to the active event loop, and " "``context`` is a ``dict`` object containing the details of the exception " "(see :meth:`call_exception_handler` documentation for details about " "context)." msgstr "" "如果 *handler* 为 ``None``,将设置默认的异常处理程序。在其他情况下,*handler* 必须是一个可调用对象且签名匹配 " "``(loop, context)``,其中 ``loop`` 是对活动事件循环的引用,而 ``context`` 是一个包含异常详情的 " "``dict`` (请查看 :meth:`call_exception_handler` 文档来获取关于上下文的更多信息)。" #: ../../library/asyncio-eventloop.rst:1491 msgid "" "If the handler is called on behalf of a :class:`~asyncio.Task` or " ":class:`~asyncio.Handle`, it is run in the :class:`contextvars.Context` of " "that task or callback handle." msgstr "" "如果针对一个 :class:`~asyncio.Task` 或 :class:`~asyncio.Handle` " "调用了该异常处理器,它将在相应任务或回调句柄的 :class:`contextvars.Context` 中运行。" #: ../../library/asyncio-eventloop.rst:1497 msgid "" "The handler may be called in the :class:`~contextvars.Context` of the task " "or handle where the exception originated." msgstr "该处理器可能会在发生异常的任务或句柄的 :class:`~contextvars.Context` 中被调用。" #: ../../library/asyncio-eventloop.rst:1502 msgid "" "Return the current exception handler, or ``None`` if no custom exception " "handler was set." msgstr "返回当前的异常处理器,如果没有设置异常处理器,则返回 ``None``。" #: ../../library/asyncio-eventloop.rst:1509 msgid "Default exception handler." msgstr "默认的异常处理器。" #: ../../library/asyncio-eventloop.rst:1511 msgid "" "This is called when an exception occurs and no exception handler is set. " "This can be called by a custom exception handler that wants to defer to the " "default handler behavior." msgstr "此方法会在发生异常且未设置异常处理程序时被调用。此方法也可以由想要具有不同于默认处理程序的行为的自定义异常处理程序来调用。" #: ../../library/asyncio-eventloop.rst:1515 msgid "" "*context* parameter has the same meaning as in " ":meth:`call_exception_handler`." msgstr "*context* 参数和 :meth:`call_exception_handler` 中的同名参数完全相同。" #: ../../library/asyncio-eventloop.rst:1520 msgid "Call the current event loop exception handler." msgstr "调用当前事件循环的异常处理器。" #: ../../library/asyncio-eventloop.rst:1522 msgid "" "*context* is a ``dict`` object containing the following keys (new keys may " "be introduced in future Python versions):" msgstr "*context* 是个包含下列键的 ``dict`` 对象 (未来版本的 Python 可能会引入新键):" #: ../../library/asyncio-eventloop.rst:1525 msgid "'message': Error message;" msgstr "'message': 错误消息;" #: ../../library/asyncio-eventloop.rst:1526 msgid "'exception' (optional): Exception object;" msgstr "'exception' (可选): 异常对象;" #: ../../library/asyncio-eventloop.rst:1527 msgid "'future' (optional): :class:`asyncio.Future` instance;" msgstr "'future' (可选): :class:`asyncio.Future` 实例;" #: ../../library/asyncio-eventloop.rst:1528 msgid "'task' (optional): :class:`asyncio.Task` instance;" msgstr "'task' (可选): :class:`asyncio.Task` 实例;" #: ../../library/asyncio-eventloop.rst:1529 msgid "'handle' (optional): :class:`asyncio.Handle` instance;" msgstr "'handle' (可选): :class:`asyncio.Handle` 实例;" #: ../../library/asyncio-eventloop.rst:1530 msgid "'protocol' (optional): :ref:`Protocol ` instance;" msgstr "'protocol' (可选): :ref:`Protocol ` 实例;" #: ../../library/asyncio-eventloop.rst:1531 msgid "'transport' (optional): :ref:`Transport ` instance;" msgstr "'transport' (可选): :ref:`Transport ` 实例;" #: ../../library/asyncio-eventloop.rst:1532 msgid "'socket' (optional): :class:`socket.socket` instance;" msgstr "'socket' (可选): :class:`socket.socket` 实例;" #: ../../library/asyncio-eventloop.rst:1533 msgid "'source_traceback' (optional): Traceback of the source;" msgstr "'source_traceback' (可选):源的回溯;" #: ../../library/asyncio-eventloop.rst:1534 msgid "'handle_traceback' (optional): Traceback of the handle;" msgstr "'handle_traceback' (可选):句柄的回溯;" #: ../../library/asyncio-eventloop.rst:1535 msgid "'asyncgen' (optional): Asynchronous generator that caused" msgstr "'asyncgen' (可选): 异步生成器,它导致了" #: ../../library/asyncio-eventloop.rst:1536 msgid "the exception." msgstr "这个异常" #: ../../library/asyncio-eventloop.rst:1540 msgid "" "This method should not be overloaded in subclassed event loops. For custom " "exception handling, use the :meth:`set_exception_handler` method." msgstr "此方法不应在子类化的事件循环中被重载。对于自定义的异常处理,请使用 :meth:`set_exception_handler` 方法。" #: ../../library/asyncio-eventloop.rst:1545 msgid "Enabling debug mode" msgstr "开启调试模式" #: ../../library/asyncio-eventloop.rst:1549 msgid "Get the debug mode (:class:`bool`) of the event loop." msgstr "获取事件循环调试模式设置 (:class:`bool`)。" #: ../../library/asyncio-eventloop.rst:1551 msgid "" "The default value is ``True`` if the environment variable " ":envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False`` " "otherwise." msgstr "" "如果环境变量 :envvar:`PYTHONASYNCIODEBUG` 是一个非空字符串,就返回 ``True``,否则就返回 ``False``。" #: ../../library/asyncio-eventloop.rst:1557 msgid "Set the debug mode of the event loop." msgstr "设置事件循环的调试模式。" #: ../../library/asyncio-eventloop.rst:1561 msgid "" "The new :ref:`Python Development Mode ` can now also be used to " "enable the debug mode." msgstr "现在也可以通过新的 :ref:`Python 开发模式 ` 来启用调试模式。" #: ../../library/asyncio-eventloop.rst:1566 msgid "" "This attribute can be used to set the minimum execution duration in seconds " "that is considered \"slow\". When debug mode is enabled, \"slow\" callbacks " "are logged." msgstr "该属性可用于设置会被视为“缓慢”的以秒数表示的最短执行时间。当启用调试模式时,“缓慢”的回调将被记录到日志。" #: ../../library/asyncio-eventloop.rst:1570 msgid "Default value is 100 milliseconds." msgstr "默认值为 100 毫秒。" #: ../../library/asyncio-eventloop.rst:1574 msgid "The :ref:`debug mode of asyncio `." msgstr ":ref:`asyncio 的调试模式 `。" #: ../../library/asyncio-eventloop.rst:1578 msgid "Running subprocesses" msgstr "运行子进程" #: ../../library/asyncio-eventloop.rst:1580 msgid "" "Methods described in this subsections are low-level. In regular async/await" " code consider using the high-level :func:`asyncio.create_subprocess_shell` " "and :func:`asyncio.create_subprocess_exec` convenience functions instead." msgstr "" "本小节所描述的方法都是低层级的。在常规 async/await 代码中请考虑改用高层级的 " ":func:`asyncio.create_subprocess_shell` 和 " ":func:`asyncio.create_subprocess_exec` 便捷函数。" #: ../../library/asyncio-eventloop.rst:1587 msgid "" "On Windows, the default event loop :class:`ProactorEventLoop` supports " "subprocesses, whereas :class:`SelectorEventLoop` does not. See " ":ref:`Subprocess Support on Windows ` for " "details." msgstr "" "在 Windows 中,默认的事件循环 :class:`ProactorEventLoop` 支持子进程,而 " ":class:`SelectorEventLoop` 不支持。参见 :ref:`Windows 中的子进程支持 `." #: ../../library/asyncio-eventloop.rst:1599 msgid "" "Create a subprocess from one or more string arguments specified by *args*." msgstr "用 *args* 指定的一个或者多个字符串型参数创建一个子进程。" #: ../../library/asyncio-eventloop.rst:1602 msgid "*args* must be a list of strings represented by:" msgstr "*args* 必须是个由下列形式的字符串组成的列表:" #: ../../library/asyncio-eventloop.rst:1604 msgid ":class:`str`;" msgstr ":class:`str`;" #: ../../library/asyncio-eventloop.rst:1605 msgid "" "or :class:`bytes`, encoded to the :ref:`filesystem encoding `." msgstr "或者由 :ref:`文件系统编码格式 ` 编码的 :class:`bytes`。" #: ../../library/asyncio-eventloop.rst:1608 msgid "" "The first string specifies the program executable, and the remaining strings" " specify the arguments. Together, string arguments form the ``argv`` of the" " program." msgstr "第一个字符串指定可执行程序,其余的字符串指定其参数。所有字符串参数共同组成了程序的 ``argv``。" #: ../../library/asyncio-eventloop.rst:1612 msgid "" "This is similar to the standard library :class:`subprocess.Popen` class " "called with ``shell=False`` and the list of strings passed as the first " "argument; however, where :class:`~subprocess.Popen` takes a single argument " "which is list of strings, *subprocess_exec* takes multiple string arguments." msgstr "" "此方法类似于调用标准库 :class:`subprocess.Popen` 类,设置 ``shell=False`` " "并将字符串列表作为第一个参数传入;但是,:class:`~subprocess.Popen` 只接受一个单独的字符串列表参数,而 " "*subprocess_exec* 接受多个字符串参数。" #: ../../library/asyncio-eventloop.rst:1618 msgid "" "The *protocol_factory* must be a callable returning a subclass of the " ":class:`asyncio.SubprocessProtocol` class." msgstr "" "*protocol_factory* 必须为一个返回 :class:`asyncio.SubprocessProtocol` 类的子类的可调用对象。" #: ../../library/asyncio-eventloop.rst:1621 msgid "Other parameters:" msgstr "其他参数:" #: ../../library/asyncio-eventloop.rst:1623 msgid "*stdin* can be any of these:" msgstr "*stdin* 可以是以下对象之一:" #: ../../library/asyncio-eventloop.rst:1625 #: ../../library/asyncio-eventloop.rst:1636 #: ../../library/asyncio-eventloop.rst:1646 msgid "a file-like object" msgstr "一个文件型对象" #: ../../library/asyncio-eventloop.rst:1626 msgid "" "an existing file descriptor (a positive integer), for example those created " "with :meth:`os.pipe`" msgstr "一个现有的文件描述符(一个正整数),例如用 :meth:`os.pipe` 创建的文件描述符" #: ../../library/asyncio-eventloop.rst:1627 #: ../../library/asyncio-eventloop.rst:1637 #: ../../library/asyncio-eventloop.rst:1647 msgid "" "the :const:`subprocess.PIPE` constant (default) which will create a new pipe" " and connect it," msgstr ":const:`subprocess.PIPE` 常量(默认),将创建并连接一个新的管道。" #: ../../library/asyncio-eventloop.rst:1629 #: ../../library/asyncio-eventloop.rst:1639 #: ../../library/asyncio-eventloop.rst:1649 msgid "" "the value ``None`` which will make the subprocess inherit the file " "descriptor from this process" msgstr "``None`` 值,这将使得子进程继承来自此进程的文件描述符" #: ../../library/asyncio-eventloop.rst:1631 #: ../../library/asyncio-eventloop.rst:1641 #: ../../library/asyncio-eventloop.rst:1651 msgid "" "the :const:`subprocess.DEVNULL` constant which indicates that the special " ":data:`os.devnull` file will be used" msgstr ":const:`subprocess.DEVNULL` 常量,这表示将使用特殊的 :data:`os.devnull` 文件" #: ../../library/asyncio-eventloop.rst:1634 msgid "*stdout* can be any of these:" msgstr "*stdout* 可以是以下对象之一:" #: ../../library/asyncio-eventloop.rst:1644 msgid "*stderr* can be any of these:" msgstr "*stderr* 可以是以下对象之一:" #: ../../library/asyncio-eventloop.rst:1653 msgid "" "the :const:`subprocess.STDOUT` constant which will connect the standard " "error stream to the process' standard output stream" msgstr ":const:`subprocess.STDOUT` 常量,将把标准错误流连接到进程的标准输出流" #: ../../library/asyncio-eventloop.rst:1656 msgid "" "All other keyword arguments are passed to :class:`subprocess.Popen` without " "interpretation, except for *bufsize*, *universal_newlines*, *shell*, *text*," " *encoding* and *errors*, which should not be specified at all." msgstr "" "所有其他关键字参数会被不加解释地传给 :class:`subprocess.Popen`,除了 *bufsize*, " "*universal_newlines*, *shell*, *text*, *encoding* 和 *errors*,它们都不应当被指定。" #: ../../library/asyncio-eventloop.rst:1661 msgid "" "The ``asyncio`` subprocess API does not support decoding the streams as " "text. :func:`bytes.decode` can be used to convert the bytes returned from " "the stream to text." msgstr "" "``asyncio`` 子进程 API 不支持将流解码为文本。可以使用 :func:`bytes.decode` 来将从流返回的字节串转换为文本。" #: ../../library/asyncio-eventloop.rst:1665 msgid "" "If a file-like object passed as *stdin*, *stdout* or *stderr* represents a " "pipe, then the other side of this pipe should be registered with " ":meth:`~loop.connect_write_pipe` or :meth:`~loop.connect_read_pipe` for use " "with the event loop." msgstr "" "如果作为 *stdin*, *stdout* 或 *stderr* 传入的文件型对象是代表一个管道,则该管道的另一端应当用 " ":meth:`~loop.connect_write_pipe` 或 :meth:`~loop.connect_read_pipe` " "来注册以配合事件循环使用。" #: ../../library/asyncio-eventloop.rst:1670 msgid "" "See the constructor of the :class:`subprocess.Popen` class for documentation" " on other arguments." msgstr "其他参数的文档,请参阅 :class:`subprocess.Popen` 类的构造函数。" #: ../../library/asyncio-eventloop.rst:1673 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`asyncio.SubprocessTransport` base class and *protocol* is an " "object instantiated by the *protocol_factory*." msgstr "" "返回一对 ``(transport, protocol)``,其中 *transport* 来自 " ":class:`asyncio.SubprocessTransport` 基类而 *protocol* 是由 *protocol_factory* " "所实例化的对象。" #: ../../library/asyncio-eventloop.rst:1677 #: ../../library/asyncio-eventloop.rst:1703 msgid "" "If the transport is closed or is garbage collected, the child process is " "killed if it is still running." msgstr "如果传输被关闭或作为垃圾被回收,则当子进程仍在运行时它将被杀掉。" #: ../../library/asyncio-eventloop.rst:1685 msgid "" "Create a subprocess from *cmd*, which can be a :class:`str` or a " ":class:`bytes` string encoded to the :ref:`filesystem encoding `, using the platform's \"shell\" syntax." msgstr "" "基于 *cmd* 创建一个子进程,该参数可以是一个 :class:`str` 或者按 :ref:`文件系统编码格式 ` 编码得到的 :class:`bytes`,使用平台的 \"shell\" 语法。" #: ../../library/asyncio-eventloop.rst:1690 msgid "" "This is similar to the standard library :class:`subprocess.Popen` class " "called with ``shell=True``." msgstr "这类似于用 ``shell=True`` 调用标准库的 :class:`subprocess.Popen` 类。" #: ../../library/asyncio-eventloop.rst:1693 msgid "" "The *protocol_factory* must be a callable returning a subclass of the " ":class:`SubprocessProtocol` class." msgstr "*protocol_factory* 必须为一个返回 :class:`SubprocessProtocol` 类的子类的可调用对象。" #: ../../library/asyncio-eventloop.rst:1696 msgid "" "See :meth:`~loop.subprocess_exec` for more details about the remaining " "arguments." msgstr "请参阅 :meth:`~loop.subprocess_exec` 了解有关其余参数的详情。" #: ../../library/asyncio-eventloop.rst:1699 msgid "" "Returns a pair of ``(transport, protocol)``, where *transport* conforms to " "the :class:`SubprocessTransport` base class and *protocol* is an object " "instantiated by the *protocol_factory*." msgstr "" "返回一对 ``(transport, protocol)``,其中 *transport* 来自 " ":class:`SubprocessTransport` 基类而 *protocol* 是由 *protocol_factory* 所实例化的对象。" #: ../../library/asyncio-eventloop.rst:1707 msgid "" "It is the application's responsibility to ensure that all whitespace and " "special characters are quoted appropriately to avoid `shell injection " "`_ " "vulnerabilities. The :func:`shlex.quote` function can be used to properly " "escape whitespace and special characters in strings that are going to be " "used to construct shell commands." msgstr "" "应用程序要负责确保正确地转义所有空白字符和特殊字符以防止 `shell 注入 " "`_ 漏洞。 " ":func:`shlex.quote` 函数可以被用来正确地转义字符串中可能被用来构造 shell 命令的空白字符和特殊字符。" #: ../../library/asyncio-eventloop.rst:1716 msgid "Callback handles" msgstr "回调处理" #: ../../library/asyncio-eventloop.rst:1720 msgid "" "A callback wrapper object returned by :meth:`loop.call_soon`, " ":meth:`loop.call_soon_threadsafe`." msgstr "" "由 :meth:`loop.call_soon`, :meth:`loop.call_soon_threadsafe` 所返回的回调包装器对象。" #: ../../library/asyncio-eventloop.rst:1725 msgid "" "Return the :class:`contextvars.Context` object associated with the handle." msgstr "返回关联到该句柄的 :class:`contextvars.Context` 对象。" #: ../../library/asyncio-eventloop.rst:1732 msgid "" "Cancel the callback. If the callback has already been canceled or executed," " this method has no effect." msgstr "取消回调。如果此回调已被取消或已被执行,此方法将没有任何效果。" #: ../../library/asyncio-eventloop.rst:1737 msgid "Return ``True`` if the callback was cancelled." msgstr "如果此回调已被取消则返回 ``True``。" #: ../../library/asyncio-eventloop.rst:1743 msgid "" "A callback wrapper object returned by :meth:`loop.call_later`, and " ":meth:`loop.call_at`." msgstr "由 :meth:`loop.call_later` 和 :meth:`loop.call_at` 所返回的回调包装器对象。" #: ../../library/asyncio-eventloop.rst:1746 msgid "This class is a subclass of :class:`Handle`." msgstr "这个类是 :class:`Handle` 的子类。" #: ../../library/asyncio-eventloop.rst:1750 msgid "Return a scheduled callback time as :class:`float` seconds." msgstr "返回加入计划任务的回调时间,以 :class:`float` 值表示的秒数。" #: ../../library/asyncio-eventloop.rst:1752 msgid "" "The time is an absolute timestamp, using the same time reference as " ":meth:`loop.time`." msgstr "时间值是一个绝对时间戳,使用与 :meth:`loop.time` 相同的时间引用。" #: ../../library/asyncio-eventloop.rst:1759 msgid "Server objects" msgstr "服务器对象" #: ../../library/asyncio-eventloop.rst:1761 msgid "" "Server objects are created by :meth:`loop.create_server`, " ":meth:`loop.create_unix_server`, :func:`start_server`, and " ":func:`start_unix_server` functions." msgstr "" "Server 对象可使用 :meth:`loop.create_server`, :meth:`loop.create_unix_server`, " ":func:`start_server` 和 :func:`start_unix_server` 等函数来创建。" #: ../../library/asyncio-eventloop.rst:1765 msgid "Do not instantiate the :class:`Server` class directly." msgstr "请不要直接实例化 :class:`Server` 类。" #: ../../library/asyncio-eventloop.rst:1769 msgid "" "*Server* objects are asynchronous context managers. When used in an ``async" " with`` statement, it's guaranteed that the Server object is closed and not " "accepting new connections when the ``async with`` statement is completed::" msgstr "" "*Server* 对象是异步上下文管理器。当用于 ``async with`` 语句时,异步上下文管理器可以确保 Server 对象被关闭,并且在 " "``async with`` 语句完成后,不接受新的连接::" #: ../../library/asyncio-eventloop.rst:1774 msgid "" "srv = await loop.create_server(...)\n" "\n" "async with srv:\n" " # some code\n" "\n" "# At this point, srv is closed and no longer accepts new connections." msgstr "" "srv = await loop.create_server(...)\n" "\n" "async with srv:\n" " # 一些代码\n" "\n" "# 此时,srv 已关闭并不再接受新的连接。" #: ../../library/asyncio-eventloop.rst:1782 msgid "Server object is an asynchronous context manager since Python 3.7." msgstr "从 Python 3.7 开始,Server 对象是一个异步上下文管理器。" #: ../../library/asyncio-eventloop.rst:1785 msgid "" "This class was exposed publicly as ``asyncio.Server`` in Python 3.9.11, " "3.10.3 and 3.11." msgstr "这个类在 Python 3.9.11, 3.10.3 和 3.11 中作为 ``asyncio.Server`` 对外公开。" #: ../../library/asyncio-eventloop.rst:1790 msgid "" "Stop serving: close listening sockets and set the :attr:`sockets` attribute " "to ``None``." msgstr "停止服务:关闭监听的套接字并且设置 :attr:`sockets` 属性为 ``None``。" #: ../../library/asyncio-eventloop.rst:1793 msgid "" "The sockets that represent existing incoming client connections are left " "open." msgstr "用于表示已经连进来的客户端连接会保持打开的状态。" #: ../../library/asyncio-eventloop.rst:1796 msgid "" "The server is closed asynchronously; use the :meth:`wait_closed` coroutine " "to wait until the server is closed (and no more connections are active)." msgstr "服务器是被异步关闭的;使用 :meth:`wait_closed` 协程来等待服务器关闭(将不再有激活的连接)。" #: ../../library/asyncio-eventloop.rst:1802 msgid "Close all existing incoming client connections." msgstr "关闭所有现有的传入客户端连接。" #: ../../library/asyncio-eventloop.rst:1804 msgid "" "Calls :meth:`~asyncio.BaseTransport.close` on all associated transports." msgstr "在所有关联的传输上调用 :meth:`~asyncio.BaseTransport.close`。" #: ../../library/asyncio-eventloop.rst:1807 msgid "" ":meth:`close` should be called before :meth:`close_clients` when closing the" " server to avoid races with new clients connecting." msgstr "当关闭服务器时 :meth:`close` 应当在 :meth:`close_clients` 之前被调用以避免与新的客户端连接发生竞争。" #: ../../library/asyncio-eventloop.rst:1814 msgid "" "Close all existing incoming client connections immediately, without waiting " "for pending operations to complete." msgstr "立即关闭所有现有的传入客户端连接,无需等待挂起的操作完成。" #: ../../library/asyncio-eventloop.rst:1817 msgid "" "Calls :meth:`~asyncio.WriteTransport.abort` on all associated transports." msgstr "在所有关联的传输上调用 :meth:`~asyncio.WriteTransport.abort`。" #: ../../library/asyncio-eventloop.rst:1820 msgid "" ":meth:`close` should be called before :meth:`abort_clients` when closing the" " server to avoid races with new clients connecting." msgstr "当关闭服务器时应当在 :meth:`abort_clients` 之前调用 :meth:`close` 以避免与新的客户端连接发生竞争。" #: ../../library/asyncio-eventloop.rst:1827 msgid "Return the event loop associated with the server object." msgstr "返回与服务器对象相关联的事件循环。" #: ../../library/asyncio-eventloop.rst:1834 msgid "Start accepting connections." msgstr "开始接受连接。" #: ../../library/asyncio-eventloop.rst:1836 msgid "" "This method is idempotent, so it can be called when the server is already " "serving." msgstr "此方法是幂等的,所以它可在服务器已在运行时被调用。" #: ../../library/asyncio-eventloop.rst:1839 msgid "" "The *start_serving* keyword-only parameter to :meth:`loop.create_server` and" " :meth:`asyncio.start_server` allows creating a Server object that is not " "accepting connections initially. In this case ``Server.start_serving()``, " "or :meth:`Server.serve_forever` can be used to make the Server start " "accepting connections." msgstr "" "传给 :meth:`loop.create_server` 和 :meth:`asyncio.start_server` 的 " "*start_serving* 仅限关键字形参允许创建不接受初始连接的 Server 对象。在此情况下可以使用 " "``Server.start_serving()`` 或 :meth:`Server.serve_forever` 让 Server 对象开始接受连接。" #: ../../library/asyncio-eventloop.rst:1851 msgid "" "Start accepting connections until the coroutine is cancelled. Cancellation " "of ``serve_forever`` task causes the server to be closed." msgstr "开始接受连接,直到协程被取消。``serve_forever`` 任务的取消将导致服务器被关闭。" #: ../../library/asyncio-eventloop.rst:1855 msgid "" "This method can be called if the server is already accepting connections. " "Only one ``serve_forever`` task can exist per one *Server* object." msgstr "如果服务器已经在接受连接了,这个方法可以被调用。每个 *Server* 对象,仅能有一个 ``serve_forever`` 任务。" #: ../../library/asyncio-eventloop.rst:1861 msgid "" "async def client_connected(reader, writer):\n" " # Communicate with the client with\n" " # reader/writer streams. For example:\n" " await reader.readline()\n" "\n" "async def main(host, port):\n" " srv = await asyncio.start_server(\n" " client_connected, host, port)\n" " await srv.serve_forever()\n" "\n" "asyncio.run(main('127.0.0.1', 0))" msgstr "" "async def client_connected(reader, writer):\n" " # 使用 reader/writer 流与客户端通信。例如:\n" " await reader.readline()\n" "\n" "async def main(host, port):\n" " srv = await asyncio.start_server(\n" " client_connected, host, port)\n" " await srv.serve_forever()\n" "\n" "asyncio.run(main('127.0.0.1', 0))" #: ../../library/asyncio-eventloop.rst:1877 msgid "Return ``True`` if the server is accepting new connections." msgstr "如果服务器正在接受新连接的状态,返回 ``True``。" #: ../../library/asyncio-eventloop.rst:1884 msgid "" "Wait until the :meth:`close` method completes and all active connections " "have finished." msgstr "等待直到 :meth:`close` 方法完成且所有活动的连接结束。" #: ../../library/asyncio-eventloop.rst:1889 msgid "" "List of socket-like objects, ``asyncio.trsock.TransportSocket``, which the " "server is listening on." msgstr "由类套接字对象组成的列表 ``asyncio.trsock.TransportSocket``,服务器将监听这些对象。" #: ../../library/asyncio-eventloop.rst:1892 msgid "" "Prior to Python 3.7 ``Server.sockets`` used to return an internal list of " "server sockets directly. In 3.7 a copy of that list is returned." msgstr "" "在 Python 3.7 之前 ``Server.sockets`` 会直接返回内部的服务器套接字列表。在 3.7 版则会返回该列表的副本。" #: ../../library/asyncio-eventloop.rst:1902 msgid "Event loop implementations" msgstr "事件循环实现" #: ../../library/asyncio-eventloop.rst:1904 msgid "" "asyncio ships with two different event loop implementations: " ":class:`SelectorEventLoop` and :class:`ProactorEventLoop`." msgstr "" "asyncio 带有两种不同的事件循环实现::class:`SelectorEventLoop` 和 " ":class:`ProactorEventLoop`." #: ../../library/asyncio-eventloop.rst:1907 msgid "By default asyncio is configured to use :class:`EventLoop`." msgstr "在默认情况下 asyncio 将被配置为使用 :class:`EventLoop`。" #: ../../library/asyncio-eventloop.rst:1912 msgid "" "A subclass of :class:`AbstractEventLoop` based on the :mod:`selectors` " "module." msgstr "基于 :mod:`selectors` 模块的 :class:`AbstractEventLoop` 的子类。" #: ../../library/asyncio-eventloop.rst:1915 msgid "" "Uses the most efficient *selector* available for the given platform. It is " "also possible to manually configure the exact selector implementation to be " "used::" msgstr "使用给定平台中最高效的可用 *selector*。也可以手动配置要使用的特定 selector::" #: ../../library/asyncio-eventloop.rst:1919 msgid "" "import asyncio\n" "import selectors\n" "\n" "async def main():\n" " ...\n" "\n" "loop_factory = lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())\n" "asyncio.run(main(), loop_factory=loop_factory)" msgstr "" "import asyncio\n" "import selectors\n" "\n" "async def main():\n" " ...\n" "\n" "loop_factory = lambda: asyncio.SelectorEventLoop(selectors.SelectSelector())\n" "asyncio.run(main(), loop_factory=loop_factory)" #: ../../library/asyncio-eventloop.rst:1934 msgid "" "A subclass of :class:`AbstractEventLoop` for Windows that uses \"I/O " "Completion Ports\" (IOCP)." msgstr "" "使用 \"I/O Completion Ports\" (IOCP) 的针对 Windows 的 :class:`AbstractEventLoop` " "子类。" #: ../../library/asyncio-eventloop.rst:1940 msgid "" "`MSDN documentation on I/O Completion Ports " "`_." msgstr "" "`有关 I/O 完成端口的 MSDN 文档 `_." #: ../../library/asyncio-eventloop.rst:1945 msgid "" "An alias to the most efficient available subclass of " ":class:`AbstractEventLoop` for the given platform." msgstr "在给定平台上可用的最高效的 :class:`AbstractEventLoop` 子类的别名。" #: ../../library/asyncio-eventloop.rst:1948 msgid "" "It is an alias to :class:`SelectorEventLoop` on Unix and " ":class:`ProactorEventLoop` on Windows." msgstr "" "它在 Unix 上是 :class:`SelectorEventLoop` 的别名而在 Windows 上是 " ":class:`ProactorEventLoop` 的别名。" #: ../../library/asyncio-eventloop.rst:1954 msgid "Abstract base class for asyncio-compliant event loops." msgstr "asyncio 兼容事件循环的抽象基类。" #: ../../library/asyncio-eventloop.rst:1956 msgid "" "The :ref:`asyncio-event-loop-methods` section lists all methods that an " "alternative implementation of ``AbstractEventLoop`` should have defined." msgstr "" ":ref:`asyncio-event-loop-methods` 一节列出了 ``AbstractEventLoop`` " "的替代实现应当要定义的所有方法。" #: ../../library/asyncio-eventloop.rst:1962 msgid "Examples" msgstr "例子" #: ../../library/asyncio-eventloop.rst:1964 msgid "" "Note that all examples in this section **purposefully** show how to use the " "low-level event loop APIs, such as :meth:`loop.run_forever` and " ":meth:`loop.call_soon`. Modern asyncio applications rarely need to be " "written this way; consider using the high-level functions like " ":func:`asyncio.run`." msgstr "" "请注意本节中的所有示例都 **有意地** 演示了如何使用低层级的事件循环 API,例如 :meth:`loop.run_forever` 和 " ":meth:`loop.call_soon`。现代的 asyncio 应用很少需要以这样的方式编写;请考虑使用高层级的函数例如 " ":func:`asyncio.run`." #: ../../library/asyncio-eventloop.rst:1974 msgid "Hello World with call_soon()" msgstr "call_soon() 的 Hello World 示例。" #: ../../library/asyncio-eventloop.rst:1976 msgid "" "An example using the :meth:`loop.call_soon` method to schedule a callback. " "The callback displays ``\"Hello World\"`` and then stops the event loop::" msgstr "" "一个使用 :meth:`loop.call_soon` 方法来安排回调的示例。回调会显示 ``\"Hello World\"`` 然后停止事件循环::" #: ../../library/asyncio-eventloop.rst:1980 msgid "" "import asyncio\n" "\n" "def hello_world(loop):\n" " \"\"\"A callback to print 'Hello World' and stop the event loop\"\"\"\n" " print('Hello World')\n" " loop.stop()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "# Schedule a call to hello_world()\n" "loop.call_soon(hello_world, loop)\n" "\n" "# Blocking call interrupted by loop.stop()\n" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.close()" msgstr "" "import asyncio\n" "\n" "def hello_world(loop):\n" " \"\"\"打印 'Hello World' 并停止事件循环的回调\"\"\"\n" " print('Hello World')\n" " loop.stop()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "# 将对 hello_world() 的调用加入计划任务\n" "loop.call_soon(hello_world, loop)\n" "\n" "# 阻塞调用被 loop.stop() 中断\n" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.close()" #: ../../library/asyncio-eventloop.rst:2000 msgid "" "A similar :ref:`Hello World ` example created with a coroutine " "and the :func:`run` function." msgstr "一个类似的 :ref:`Hello World ` 示例,使用协程和 :func:`run` 函数创建。" #: ../../library/asyncio-eventloop.rst:2007 msgid "Display the current date with call_later()" msgstr "使用 call_later() 来展示当前的日期" #: ../../library/asyncio-eventloop.rst:2009 msgid "" "An example of a callback displaying the current date every second. The " "callback uses the :meth:`loop.call_later` method to reschedule itself after " "5 seconds, and then stops the event loop::" msgstr "" "一个每秒刷新显示当前日期的示例。回调使用 :meth:`loop.call_later` 方法在 5 秒后将自身重新加入计划日程,然后停止事件循环::" #: ../../library/asyncio-eventloop.rst:2013 msgid "" "import asyncio\n" "import datetime as dt\n" "\n" "def display_date(end_time, loop):\n" " print(dt.datetime.now())\n" " if (loop.time() + 1.0) < end_time:\n" " loop.call_later(1, display_date, end_time, loop)\n" " else:\n" " loop.stop()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "# Schedule the first call to display_date()\n" "end_time = loop.time() + 5.0\n" "loop.call_soon(display_date, end_time, loop)\n" "\n" "# Blocking call interrupted by loop.stop()\n" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.close()" msgstr "" "import asyncio\n" "import datetime as dt\n" "\n" "def display_date(end_time, loop):\n" " print(dt.datetime.now())\n" " if (loop.time() + 1.0) < end_time:\n" " loop.call_later(1, display_date, end_time, loop)\n" " else:\n" " loop.stop()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "# 将对 display_date() 的第一次调用加入计划任务\n" "end_time = loop.time() + 5.0\n" "loop.call_soon(display_date, end_time, loop)\n" "\n" "# 被 loop.stop() 中断的阻塞调用\n" "try:\n" " loop.run_forever()\n" "finally:\n" " loop.close()" #: ../../library/asyncio-eventloop.rst:2037 msgid "" "A similar :ref:`current date ` example created with a" " coroutine and the :func:`run` function." msgstr "" "一个类似的 :ref:`current date ` 示例,使用协程和 :func:`run` 函数创建。" #: ../../library/asyncio-eventloop.rst:2044 msgid "Watch a file descriptor for read events" msgstr "监控一个文件描述符的读事件" #: ../../library/asyncio-eventloop.rst:2046 msgid "" "Wait until a file descriptor received some data using the " ":meth:`loop.add_reader` method and then close the event loop::" msgstr "使用 :meth:`loop.add_reader` 方法,等到文件描述符收到一些数据,然后关闭事件循环::" #: ../../library/asyncio-eventloop.rst:2049 msgid "" "import asyncio\n" "from socket import socketpair\n" "\n" "# Create a pair of connected file descriptors\n" "rsock, wsock = socketpair()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "def reader():\n" " data = rsock.recv(100)\n" " print(\"Received:\", data.decode())\n" "\n" " # We are done: unregister the file descriptor\n" " loop.remove_reader(rsock)\n" "\n" " # Stop the event loop\n" " loop.stop()\n" "\n" "# Register the file descriptor for read event\n" "loop.add_reader(rsock, reader)\n" "\n" "# Simulate the reception of data from the network\n" "loop.call_soon(wsock.send, 'abc'.encode())\n" "\n" "try:\n" " # Run the event loop\n" " loop.run_forever()\n" "finally:\n" " # We are done. Close sockets and the event loop.\n" " rsock.close()\n" " wsock.close()\n" " loop.close()" msgstr "" "import asyncio\n" "from socket import socketpair\n" "\n" "# 创建一对已连接的文件描述符\n" "rsock, wsock = socketpair()\n" "\n" "loop = asyncio.new_event_loop()\n" "\n" "def reader():\n" " data = rsock.recv(100)\n" " print(\"Received:\", data.decode())\n" "\n" " # 已完成:注销文件描述符\n" " loop.remove_reader(rsock)\n" "\n" " # 停止事件循环\n" " loop.stop()\n" "\n" "# 为读取事件注册文件描述符\n" "loop.add_reader(rsock, reader)\n" "\n" "# 模拟从网络接收数据\n" "loop.call_soon(wsock.send, 'abc'.encode())\n" "\n" "try:\n" " # 运行事件循环\n" " loop.run_forever()\n" "finally:\n" " # 已完成。关闭套接字和事件循环。\n" " rsock.close()\n" " wsock.close()\n" " loop.close()" #: ../../library/asyncio-eventloop.rst:2084 msgid "" "A similar :ref:`example ` using " "transports, protocols, and the :meth:`loop.create_connection` method." msgstr "" "一个类似的 :ref:`示例 `,使用传输、协议和 " ":meth:`loop.create_connection` 方法创建。" #: ../../library/asyncio-eventloop.rst:2088 msgid "" "Another similar :ref:`example ` " "using the high-level :func:`asyncio.open_connection` function and streams." msgstr "" "另一个类似的 :ref:`示例 `,使用了高层级的 " ":func:`asyncio.open_connection` 函数和流。" #: ../../library/asyncio-eventloop.rst:2096 msgid "Set signal handlers for SIGINT and SIGTERM" msgstr "为 SIGINT 和 SIGTERM 设置信号处理器" #: ../../library/asyncio-eventloop.rst:2098 msgid "(This ``signal`` example only works on Unix.)" msgstr "(这个 ``signal`` 示例只适用于 Unix。)" #: ../../library/asyncio-eventloop.rst:2100 msgid "" "Register handlers for signals :const:`~signal.SIGINT` and " ":const:`~signal.SIGTERM` using the :meth:`loop.add_signal_handler` method::" msgstr "" "使用 :meth:`loop.add_signal_handler` 方法为信号 :const:`~signal.SIGINT` 和 " ":const:`~signal.SIGTERM` 注册处理器::" #: ../../library/asyncio-eventloop.rst:2103 msgid "" "import asyncio\n" "import functools\n" "import os\n" "import signal\n" "\n" "def ask_exit(signame, loop):\n" " print(\"got signal %s: exit\" % signame)\n" " loop.stop()\n" "\n" "async def main():\n" " loop = asyncio.get_running_loop()\n" "\n" " for signame in {'SIGINT', 'SIGTERM'}:\n" " loop.add_signal_handler(\n" " getattr(signal, signame),\n" " functools.partial(ask_exit, signame, loop))\n" "\n" " await asyncio.sleep(3600)\n" "\n" "print(\"Event loop running for 1 hour, press Ctrl+C to interrupt.\")\n" "print(f\"pid {os.getpid()}: send SIGINT or SIGTERM to exit.\")\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "import functools\n" "import os\n" "import signal\n" "\n" "def ask_exit(signame, loop):\n" " print(\"got signal %s: exit\" % signame)\n" " loop.stop()\n" "\n" "async def main():\n" " loop = asyncio.get_running_loop()\n" "\n" " for signame in {'SIGINT', 'SIGTERM'}:\n" " loop.add_signal_handler(\n" " getattr(signal, signame),\n" " functools.partial(ask_exit, signame, loop))\n" "\n" " await asyncio.sleep(3600)\n" "\n" "print(\"Event loop running for 1 hour, press Ctrl+C to interrupt.\")\n" "print(f\"pid {os.getpid()}: send SIGINT or SIGTERM to exit.\")\n" "\n" "asyncio.run(main())"