-

Event Loop

-

原始碼:Lib/asyncio/events.pyLib/asyncio/base_events.py

+

事件迴圈

+

原始碼: Lib/asyncio/events.pyLib/asyncio/base_events.py


-

Preface

-

The event loop is the core of every asyncio application. -Event loops run asynchronous tasks and callbacks, perform network -IO operations, and run subprocesses.

-

Application developers should typically use the high-level asyncio functions, -such as asyncio.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.

-

Obtaining the Event Loop

-

The following low-level functions can be used to get, set, or create -an event loop:

+

前言

+

事件迴圈是每個 asyncio 應用程式的核心。事件迴圈執行非同步任務和回呼、執行網路 IO 操作並啟動子行程。

+

應用程式開發人員通常應使用高階的 asyncio 函式,例如 asyncio.run(),並且很少需要參照事件迴圈物件或呼叫其方法。本節主要針對那些需要更細粒度控制事件迴圈行為的低階程式碼、函式庫和框架的作者。

+

取得事件迴圈

+

以下的低階函式可用於取得、設置或建立事件迴圈:

asyncio.get_running_loop()
-

Return the running event loop in the current OS thread.

-

Raise a RuntimeError if there is no running event loop.

-

This function can only be called from a coroutine or a callback.

+

在當前作業系統執行緒中回傳正在運行的事件迴圈。

+

如果沒有運行的事件迴圈,則引發 RuntimeError

+

此函式只能從協程或回呼函式中呼叫。

Added in version 3.7.

@@ -325,146 +318,112 @@

瀏覽

asyncio.get_event_loop()
-

Get the current event loop.

-

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.

-

If there is no running event loop set, the function will return -the result of the get_event_loop_policy().get_event_loop() call.

-

Because this function has rather complex behavior (especially -when custom event loop policies are in use), using the -get_running_loop() function is preferred to get_event_loop() -in coroutines and callbacks.

-

As noted above, consider using the higher-level asyncio.run() function, -instead of using these lower level functions to manually create and close an -event loop.

+

取得目前的事件迴圈。

+

當從協程或回呼函式呼叫此函式(例如,使用 call_soon 或類似的 API 於排程呼叫),此函式將永遠回傳正在運行的事件迴圈。

+

如果沒有設定正在運行的事件迴圈,該函式將回傳 get_event_loop_policy().get_event_loop() 呼叫的結果。

+

由於此函式具有相當複雜的行為(尤其是在使用自訂事件迴圈策略時),在協程和回呼函式中,建議使用 get_running_loop() 函式,而不是 get_event_loop()

+

如上所述,可以考慮使用高階的 asyncio.run() 函式,而不是使用這些較低階的函式手動建立和關閉事件迴圈。

-

在 3.12 版之後被棄用: Deprecation warning is emitted if there is no current event loop. -In some future Python release this will become an error.

+

在 3.12 版之後被棄用: 如果沒有當前事件迴圈,則會發出棄用警告。在未來的某個 Python 發行版中,這將變成錯誤。

asyncio.set_event_loop(loop)
-

Set loop as the current event loop for the current OS thread.

+

loop 設置為當前 OS 執行緒的當前事件迴圈。

asyncio.new_event_loop()
-

Create and return a new event loop object.

+

建立並回傳新的事件迴圈物件。

-

Note that the behaviour of get_event_loop(), set_event_loop(), -and new_event_loop() functions can be altered by -setting a custom event loop policy.

+

請注意 get_event_loop()set_event_loop()new_event_loop() 函式的行為可以透過設定自訂事件迴圈策略進行調整。

目錄

-

This documentation page contains the following sections:

+

本頁文件包含以下章節:

-

Event Loop Methods

-

Event loops have low-level APIs for the following:

+

事件迴圈方法

+

事件迴圈提供以下低階 API:

-

Running and stopping the loop

+

啟動和停止迴圈

loop.run_until_complete(future)
-

Run until the future (an instance of Future) has -completed.

-

If the argument is a coroutine object it -is implicitly scheduled to run as a asyncio.Task.

-

Return the Future's result or raise its exception.

+

運行直到 future (一個 Future 實例)完成。

+

如果引數是協程物件,則它將被隱式排程為 asyncio.Task 運行。

+

回傳 Future 的結果或引發其例外。

loop.run_forever()
-

Run the event loop until stop() is called.

-

If stop() is called before 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.

-

If stop() is called while 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 run_forever() or -run_until_complete() is called.

+

運行事件迴圈直到 stop() 被呼叫。

+

如果在呼叫 run_forever() 之前呼叫 stop(),則迴圈將使用超時為零的方式輪詢 I/O 選擇器,運行所有回應 I/O 事件(以及已經排程的事件)的回呼函數,然後退出。

+

如果在 run_forever() 運行時呼叫 stop(),則迴圈將運行當前批次的回呼函式,然後退出。請注意,由回呼函式排程的新回呼在此情況下不會運行;而是在下次呼叫 run_forever()run_until_complete() 時運行。

loop.stop()
-

Stop the event loop.

+

停止事件迴圈。

loop.is_running()
-

Return True if the event loop is currently running.

+

如果事件迴圈當前正在運行,則回傳 True

loop.is_closed()
-

Return True if the event loop was closed.

+

如果事件迴圈已關閉,則回傳 True

loop.close()
-

Close the event loop.

-

The loop must not be running when this function is called. -Any pending callbacks will be discarded.

-

This method clears all queues and shuts down the executor, but does -not wait for the executor to finish.

-

This method is idempotent and irreversible. No other methods -should be called after the event loop is closed.

+

關閉事件迴圈。

+

不得於迴圈運行中呼叫此函式。將丟棄任何待處理的回呼。

+

此方法清除所有佇列並關閉執行器,但不等待執行器完成。

+

此方法是冪等且不可逆的。在事件迴圈關閉後不應呼叫其他方法。

coroutine loop.shutdown_asyncgens()
-

Schedule all currently open asynchronous generator objects to -close with an 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.

-

Note that there is no need to call this function when -asyncio.run() is used.

+

排程所有當前打開的非同步產生器物件使用 aclose() 呼叫來關閉。呼叫此方法後,如果疊代新的非同步產生器,事件迴圈將發出警告。應該使用此方法可靠地完成所有已排程的非同步產生器。

+

請注意,使用 asyncio.run() 時不需要呼叫此函式。

範例:

try:
     loop.run_forever()
@@ -481,22 +440,12 @@ 

Running and stopping
coroutine loop.shutdown_default_executor(timeout=None)
-

Schedule the closure of the default executor and wait for it to join all of -the threads in the ThreadPoolExecutor. -Once this method has been called, -using the default executor with loop.run_in_executor() -will raise a RuntimeError.

-

The timeout parameter specifies the amount of time -(in float seconds) the executor will be given to finish joining. -With the default, None, -the executor is allowed an unlimited amount of time.

-

If the timeout is reached, a RuntimeWarning is emitted -and the default executor is terminated -without waiting for its threads to finish joining.

+

排程預設執行器的關閉,並等待它加入 ThreadPoolExecutor 中的所有執行緒。一旦呼叫了此方法,使用預設執行器與 loop.run_in_executor() 將引發 RuntimeError

+

timeout 參數指定執行器完成加入所需的時間(以 float 秒為單位)。預設情況下為 None,不會限制執行器所花費的時間。

+

如果達到 timeout,將發出 RuntimeWarning 警告,預設執行器將立即終止,不等待其執行緒完成加入。

備註

-

Do not call this method when using asyncio.run(), -as the latter handles default executor shutdown automatically.

+

使用 asyncio.run() 時請勿呼叫此方法,因為後者會自動處理預設執行器的關閉。

Added in version 3.9.

@@ -508,133 +457,96 @@

Running and stopping

-

Scheduling callbacks

+

排程回呼函式

loop.call_soon(callback, *args, context=None)
-

Schedule the callback callback to be called with -args arguments at the next iteration of the event loop.

-

Return an instance of asyncio.Handle, -which can be used later to cancel the callback.

-

Callbacks are called in the order in which they are registered. -Each callback will be called exactly once.

-

The optional keyword-only context argument specifies a -custom contextvars.Context for the callback to run in. -Callbacks use the current context when no context is provided.

-

Unlike call_soon_threadsafe(), this method is not thread-safe.

+

在事件迴圈的下一次疊代中排程以 args 引數呼叫 callback callback

+

回傳 asyncio.Handle 的實例,稍後可以用於取消回呼函式。

+

回呼函式按照其註冊的順序呼叫。每個回呼函式將被呼叫恰好一次。

+

選用的僅限關鍵字引數 context 指定了要給 callback 執行的自定義 contextvars.Context。當未提供 context 時,回呼函式使用當前情境。

+

call_soon_threadsafe() 不同,此方法不是執行緒安全的。

loop.call_soon_threadsafe(callback, *args, context=None)
-

A thread-safe variant of call_soon(). When scheduling callbacks from -another thread, this function must be used, since call_soon() is not -thread-safe.

-

Raises RuntimeError if called on a loop that's been closed. -This can happen on a secondary thread when the main application is -shutting down.

-

See the concurrency and multithreading -section of the documentation.

+

這是 call_soon() 的執行緒安全變體。當從另一個執行緒排程回呼函式時,必須使用此函式,因為 call_soon() 不是執行緒安全的。

+

如果在已關閉的迴圈上呼叫,則引發 RuntimeError。在主應用程式關閉時,這可能發生在次要執行緒上。

+

請參閱文件的並行和多執行緒部分。

-

在 3.7 版的變更: The context keyword-only parameter was added. See PEP 567 -for more details.

+

在 3.7 版的變更: 新增了 context 僅限關鍵字參數。詳細資訊請參閱 PEP 567

備註

-

Most asyncio scheduling functions don't allow passing -keyword arguments. To do that, use functools.partial():

+

大多數 asyncio 排程函式不允許傳遞關鍵字引數。要傳遞關鍵字引數,請使用 functools.partial()

# will schedule "print("Hello", flush=True)"
 loop.call_soon(
     functools.partial(print, "Hello", flush=True))
 
-

Using partial objects is usually more convenient than using lambdas, -as asyncio can render partial objects better in debug and error -messages.

+

通常使用 partial 物件比使用 lambda 更方便,因為 asyncio 可以在除錯和錯誤訊息中更好地呈現 partial 物件。

-

Scheduling delayed callbacks

-

Event loop provides mechanisms to schedule callback functions -to be called at some point in the future. Event loop uses monotonic -clocks to track time.

+

排程延遲的回呼函式

+

事件迴圈提供為回呼函式排程在將來某個時間點才呼叫的機制。事件迴圈使用了單調時鐘來追蹤時間。

loop.call_later(delay, callback, *args, context=None)
-

Schedule callback to be called after the given delay -number of seconds (can be either an int or a float).

-

An instance of asyncio.TimerHandle is returned which can -be used to cancel the callback.

-

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.

-

The optional positional args will be passed to the callback when -it is called. If you want the callback to be called with keyword -arguments use functools.partial().

-

An optional keyword-only context argument allows specifying a -custom contextvars.Context for the callback to run in. -The current context is used when no context is provided.

+

排程 callback 在給定的 delay 秒數後呼叫(可以是整數或浮點數)。

+

回傳 asyncio.TimerHandle 的實例,可用於取消回呼函式。

+

callback 將只被呼叫恰好一次。如果有兩個回呼函式被排程在完全相同的時間,則其呼叫順序是不定的。

+

可選的位置引數 args 將在呼叫回呼函式時傳遞。如果要使用關鍵字引數呼叫回呼函數,請使用 functools.partial()

+

可選的僅限關鍵字 context 引數允許為 callback 指定自定義的 contextvars.Context 以提供運行。當未提供 context 時,將使用當前情境。

-

在 3.7 版的變更: The context keyword-only parameter was added. See PEP 567 -for more details.

+

在 3.7 版的變更: 新增了 context 僅限關鍵字參數。詳細資訊請參閱 PEP 567

-

在 3.8 版的變更: 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.

+

在 3.8 版的變更: 在 Python 3.7 及更早版本中,使用預設事件迴圈實作時,delay 不能超過一天。這在 Python 3.8 中已經修復。

loop.call_at(when, callback, *args, context=None)
-

Schedule callback to be called at the given absolute timestamp -when (an int or a float), using the same time reference as -loop.time().

-

This method's behavior is the same as call_later().

-

An instance of asyncio.TimerHandle is returned which can -be used to cancel the callback.

+

排程 callback 在給定的絕對時間戳 when (整數或浮點數)處呼叫,使用與 loop.time() 相同的時間參照。

+

此方法的行為與 call_later() 相同。

+

回傳 asyncio.TimerHandle 的實例,可用於取消回呼函式。

-

在 3.7 版的變更: The context keyword-only parameter was added. See PEP 567 -for more details.

+

在 3.7 版的變更: 新增了 context 僅限關鍵字參數。詳細資訊請參閱 PEP 567

-

在 3.8 版的變更: 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.

+

在 3.8 版的變更: 在 Python 3.7 及更早版本中,使用預設事件迴圈實作時,when 和當前時間之間的差值不能超過一天。這在 Python 3.8 中已經修復。

loop.time()
-

Return the current time, as a float value, according to -the event loop's internal monotonic clock.

+

根據事件迴圈的內部單調時鐘,回傳當前時間,以 float 值表示。

備註

-

在 3.8 版的變更: 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.

+

在 3.8 版的變更: 在 Python 3.7 及更早版本中,超時(相對 delay 或絕對 when)不應超過一天。這在 Python 3.8 中已經修復。

也參考

-

The asyncio.sleep() function.

+

函式 asyncio.sleep()

-

Creating Futures and Tasks

+

建立 Futures 和 Tasks

loop.create_future()
-

Create an asyncio.Future object attached to the event loop.

-

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).

+

建立附加到事件迴圈的 asyncio.Future 物件。

+

這是在 asyncio 中建立 Futures 的首選方式。這允許第三方事件迴圈提供 Future 物件的替代實作(具有更好的性能或儀器計測表現)。

Added in version 3.5.2.

@@ -643,16 +555,10 @@

Creating Futures and
loop.create_task(coro, *, name=None, context=None)
-

Schedule the execution of coroutine coro. -Return a Task object.

-

Third-party event loops can use their own subclass of Task -for interoperability. In this case, the result type is a subclass -of Task.

-

If the name argument is provided and not None, it is set as -the name of the task using Task.set_name().

-

An optional keyword-only context argument allows specifying a -custom contextvars.Context for the coro to run in. -The current context copy is created when no context is provided.

+

排程執行協程 coro。回傳 Task 物件。

+

第三方事件迴圈可以使用其自己的 Task 子類別以實現互操作性(interoperability)。在這種情況下,結果類型是 Task 的子類別。

+

如果提供了 name 引數且不為 None,則將其設置為任務的名稱,使用 Task.set_name()

+

可選的僅限關鍵字 context 引數允許為 coro 指定自定義的 contextvars.Context 以提供運行。當未提供 context 時,將建立當前情境的副本。

在 3.8 版的變更: 加入 name 參數。

@@ -664,114 +570,57 @@

Creating Futures and
loop.set_task_factory(factory)
-

Set a task factory that will be used by -loop.create_task().

-

If factory is None the default task factory will be set. -Otherwise, factory must be a callable with the signature matching -(loop, coro, context=None), where loop is a reference to the active -event loop, and coro is a coroutine object. The callable -must return a asyncio.Future-compatible object.

+

設置將由 loop.create_task() 使用的任務工廠。

+

如果 factoryNone,將設置預設的任務工廠。否則,factory 必須是一個具有匹配簽名 (loop, coro, context=None)callable,其中 loop 是有效事件迴圈的參照,coro 是一個協程物件。該可呼叫物件必須回傳一個與 asyncio.Future 相容的物件。

loop.get_task_factory()
-

Return a task factory or None if the default one is in use.

+

回傳任務工廠,如果使用預設任務工廠則回傳 None

-

Opening network connections

+

打開網路連線

coroutine loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None, all_errors=False)
-

Open a streaming transport connection to a given -address specified by host and port.

-

The socket family can be either AF_INET or -AF_INET6 depending on host (or the family -argument, if provided).

-

The socket type will be SOCK_STREAM.

-

protocol_factory must be a callable returning an -asyncio protocol implementation.

-

This method will try to establish the connection in the background. -When successful, it returns a (transport, protocol) pair.

-

The chronological synopsis of the underlying operation is as follows:

+

打開以 hostport 指定之給定地址的串流傳輸連線。

+

根據 host*(或提供的 *family 引數)的情況,socket 家族可以是 AF_INETAF_INET6

+

Socket 類型將為 SOCK_STREAM

+

protocol_factory 必須是一個回傳 asyncio protocol 實作的可呼叫函式。

+

此方法將嘗試在背景建立連線。成功時,它將回傳一對 (transport, protocol)

+

底層操作的時間軸簡介如下:

    -
  1. The connection is established and a transport -is created for it.

  2. -
  3. protocol_factory is called without arguments and is expected to -return a protocol instance.

  4. -
  5. The protocol instance is coupled with the transport by calling its -connection_made() method.

  6. -
  7. A (transport, protocol) tuple is returned on success.

  8. +
  9. 建立連線並為其建立傳輸

  10. +
  11. protocol_factory 在無引數的情況下被呼叫,並且預計回傳一個 協定 實例。

  12. +
  13. 通過呼叫其 connection_made() 方法,將協議實例與傳輸連線在一起。

  14. +
  15. 成功時回傳一個 (transport, protocol) 元組。

-

The created transport is an implementation-dependent bidirectional -stream.

-

Other arguments:

+

建立的傳輸是一個依賴實作的雙向串流。

+

其他引數:

    -
  • ssl: if given and not false, a SSL/TLS transport is created -(by default a plain TCP transport is created). If ssl is -a ssl.SSLContext object, this context is used to create -the transport; if ssl is True, a default context returned -from ssl.create_default_context() is used.

    +
  • 若有給定 ssl 且非 false,將建立 SSL/TLS 傳輸(預設建立普通 TCP 傳輸)。如果 sslssl.SSLContext 物件,則使用該情境來建立傳輸;如果 sslTrue,則使用 ssl.create_default_context() 回傳的預設情境。

  • -
  • 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).

  • -
  • family, proto, flags are the optional address family, protocol -and flags to be passed through to getaddrinfo() for host resolution. -If given, these should all be integers from the corresponding -socket module constants.

  • -
  • 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).

  • -
  • 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 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.

  • -
  • sock, if given, should be an existing, already connected -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.

    +
  • server_hostname 設置或覆蓋目標伺服器憑證將匹配的主機名稱。僅在 ssl 不為 None 時傳遞。預設情況下,將使用 host 引數的值。如果 host 為空,則沒有預設值,必須傳遞 server_hostname 的值。若 server_hostname 為空字串,將停用主機名稱匹配(這是一個嚴重的安全風險,可能導致中間人攻擊)。

  • +
  • familyprotoflags 是可選的位址家族、協議和旗標,用於傳遞至 getaddrinfo() 進行 host 解析。若有給定這些應該都是相應 socket 模組常數的整數。

  • +
  • 若有給定,happy_eyeballs_delay 會啟用此連線的 Happy Eyeballs。它應該是一個浮點數,表示等待連線嘗試完成的秒數,然後在並行啟動下一次嘗試。這是 RFC 8305 中定義的「連線嘗試延遲」。RFC 建議的合理預設值為 0.25 秒(250 毫秒)。

  • +
  • interleave 控制主機名稱解析為多個 IP 位址時的地址重新排序。若為 0 或未指定,將不執行重排序,並按 getaddrinfo() 回傳的順序嘗試位址。如果指定正整數,則按地址家族交錯排列,給定的整數直譯為 RFC 8305 中定義的「首個地址家族計數」。如果未指定 happy_eyeballs_delay,則預設值為 0,如果指定則為 1

  • +
  • 若有給定 sock 則其應為已存在且已連線的 socket.socket 物件,可供傳輸使用。如果提供了 sock,則不應指定 hostportfamilyprotoflagshappy_eyeballs_delayinterleavelocal_addr 中的任何一項。

    備註

    -

    The sock argument transfers ownership of the socket to the -transport created. To close the socket, call the transport's -close() method.

    +

    引數 sock 將 socket 所有權轉移給所建立的傳輸 socket,請呼叫傳輸的 close() 方法。

  • -
  • 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.

  • -
  • 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).

  • -
  • 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).

  • -
  • 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).

  • +
  • 若有給定 local_addr 則其為一個 (local_host, local_port) 元組,用於在本地綁定 socket。將使用 getaddrinfo() 查找 local_hostlocal_port,方式類似於 hostport

  • +
  • ssl_handshake_timeout (對於 TLS 連線)是等待 TLS 交握的時間,以秒為單位,在那之前若未完成則會中斷連線。如果為 None (預設值),則會等待 60.0 秒。

  • +
  • ssl_shutdown_timeout 是等待 SSL 關閉完成以前中斷連線的時間,以秒為單位。如果為 None (預設值),則會等待 30.0 秒。

  • +
  • all_errors 決定在無法建立連線時會引發哪些例外。預設情況下,只會引發單一 Exception:如果只有一個例外或所有錯誤訊息相同,則引發第一個例外,否則引發包含所有錯誤訊息的單一 OSError。當 all_errorsTrue 時,將引發包含所有例外的 ExceptionGroup (即使只有一個例外)。

在 3.5 版的變更: 新增 ProactorEventLoop 中的 SSL/TLS 支援。

@@ -784,121 +633,73 @@

Opening network conne

在 3.11 版的變更: 增加 ssl_shutdown_timeout 參數。

-

在 3.12 版的變更: all_errors was added.

+

在 3.12 版的變更: 已新增 all_errors

也參考

-

The open_connection() function is a high-level alternative -API. It returns a pair of (StreamReader, StreamWriter) -that can be used directly in async/await code.

+

函式 open_connection() 是高階的替代 API。它回傳一對 (StreamReader, StreamWriter) 可直接在 async/await 程式碼中使用。

coroutine loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_port=None, allow_broadcast=None, sock=None)
-

Create a datagram connection.

-

The socket family can be either AF_INET, -AF_INET6, or AF_UNIX, -depending on host (or the family argument, if provided).

-

The socket type will be SOCK_DGRAM.

-

protocol_factory must be a callable returning a -protocol implementation.

-

A tuple of (transport, protocol) is returned on success.

-

Other arguments:

+

建立一個資料報連線。

+

Socket 家族可以是 AF_INETAF_INET6AF_UNIX,視乎 host(或提供的 family 引數)而定。

+

Socket 類型將為 SOCK_DGRAM

+

protocol_factory 必須是可呼叫的函式,回傳 protocol 實作。

+

成功時回傳 (transport, protocol) 元組。

+

其他引數:

    -
  • 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().

  • -
  • 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 getaddrinfo().

  • -
  • family, proto, flags are the optional address family, protocol -and flags to be passed through to getaddrinfo() for host -resolution. If given, these should all be integers from the -corresponding socket module constants.

  • -
  • 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 socket.SO_REUSEPORT constant is not -defined then this capability is unsupported.

  • -
  • allow_broadcast tells the kernel to allow this endpoint to send -messages to the broadcast address.

  • -
  • sock can optionally be specified in order to use a preexisting, -already connected, socket.socket object to be used by the -transport. If specified, local_addr and remote_addr should be omitted -(must be None).

    +
  • local_addr,如果提供,是一個 (local_host, local_port) 元組,用於在本地綁定 socket。local_hostlocal_port 使用 getaddrinfo() 來查找。

  • +
  • remote_addr,如果提供,是一個 (remote_host, remote_port) 元組,用於將 socket 連線到遠端位址。 remote_hostremote_port 使用 getaddrinfo() 來查找。

  • +
  • familyprotoflags 是用於傳遞給 getaddrinfo() 以解析 host 的可選地址家族、協定和旗標。如果提供,這些應該都是來自相應的 socket 模組常數的整數。

  • +
  • reuse_port 告訴核心允許將此端點綁定到與其他現有端點相同的埠,只要它們在建立時都設定了此旗標。此選項不受 Windows 和某些 Unix 系統支援。如果未定義 SO_REUSEPORT 常數,則不支援此功能。

  • +
  • allow_broadcast 告訴核心允許此端點向廣播位址發送訊息。

  • +
  • sock 可以選擇性地指定,以使用預先存在且已連線的 socket.socket 物件供傳輸使用。如果指定,local_addrremote_addr 應省略(必須是 None)。

    備註

    -

    The sock argument transfers ownership of the socket to the -transport created. To close the socket, call the transport's -close() method.

    +

    引數 sock 將 socket 所有權轉移給所建立的傳輸 socket,請呼叫傳輸的 close() 方法。

-

See UDP echo client protocol and -UDP echo server protocol examples.

+

請參閱 UDP 回應用戶端協議UDP 回應伺服器協議 範例。

-

在 3.4.4 版的變更: The family, proto, flags, reuse_address, reuse_port, -allow_broadcast, and sock parameters were added.

+

在 3.4.4 版的變更: 新增 familyprotoflagsreuse_addressreuse_portallow_broadcastsock 參數。

在 3.8 版的變更: 新增對於 Windows 的支援。

-

在 3.8.1 版的變更: The reuse_address parameter is no longer supported, as using -socket.SO_REUSEADDR -poses a significant security concern for -UDP. Explicitly passing reuse_address=True will raise an exception.

-

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.

-

For supported platforms, reuse_port can be used as a replacement for -similar functionality. With reuse_port, -socket.SO_REUSEPORT -is used instead, which specifically -prevents processes with differing UIDs from assigning sockets to the same -socket address.

+

在 3.8.1 版的變更: 不再支援 reuse_address 參數,因為使用 SO_REUSEADDR 對於 UDP 存有重大的安全疑慮。明確傳遞 reuse_address=True 將引發例外。

+

當具有不同 UID 的多個行程使用 SO_REUSEADDR 將 socket 分配給相同的 UDP socket 地址時,傳入的封包可能會在 socket 之間隨機分佈。

+

對於有支援的平台,reuse_port 可以用作類似功能的替代方案。使用 reuse_port,將改為使用 SO_REUSEPORT,該選項明確禁止具有不同 UID 的行程將 socket 分配給相同的 socket 地址。

-

在 3.11 版的變更: The reuse_address parameter, disabled since Python 3.8.1, -3.7.6 and 3.6.10, has been entirely removed.

+

在 3.11 版的變更: 自 Python 3.9.0、3.8.1、3.7.6 和 3.6.10 起,已完全移除 reuse_address 參數。

coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)
-

Create a Unix connection.

-

The socket family will be AF_UNIX; socket -type will be SOCK_STREAM.

-

A tuple of (transport, protocol) is returned on success.

-

path is the name of a Unix domain socket and is required, -unless a sock parameter is specified. Abstract Unix sockets, -str, bytes, and Path paths are -supported.

-

See the documentation of the loop.create_connection() method -for information about arguments to this method.

+

建立一個 Unix 連線。

+

Socket 家族將為 AF_UNIX;socket 類型將為 SOCK_STREAM

+

成功時回傳 (transport, protocol) 元組。

+

path 是 Unix 域 socket 的名稱,除非指定 sock 參數,否則為必填。支援抽象 Unix sockets、strbytesPath 路徑。

+

有關此方法的引數資訊,請參閱 loop.create_connection() 方法的文件。

適用:Unix。

-

在 3.7 版的變更: Added the ssl_handshake_timeout parameter. -The path parameter can now be a path-like object.

+

在 3.7 版的變更: 新增 ssl_handshake_timeout 參數。path 參數現在可以是 path-like object

在 3.11 版的變更: 增加 ssl_shutdown_timeout 參數。

@@ -907,76 +708,44 @@

Opening network conne

-

Creating network servers

+

建立網路伺服器

coroutine loop.create_server(protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)
-

Create a TCP server (socket type SOCK_STREAM) listening -on port of the host address.

-

Returns a Server object.

+

建立一個 TCP 伺服器(socket 類型 SOCK_STREAM),監聽 host 位址的 port

+

回傳一個 Server 物件。

引數:

    -
  • protocol_factory must be a callable returning a -protocol implementation.

  • -
  • The host parameter can be set to several types which determine where -the server would be listening:

    +
  • protocol_factory 必須是可呼叫的函式,回傳 protocol 實作。

  • +
  • 可以將 host 參數設為幾種類型,以確定伺服器將監聽的位置:

      -
    • If host is a string, the TCP server is bound to a single network -interface specified by host.

    • -
    • If host is a sequence of strings, the TCP server is bound to all -network interfaces specified by the sequence.

    • -
    • 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).

    • +
    • 如果 host 是字串,則 TCP 伺服器綁定到由 host 指定的單個網路介面。

    • +
    • 如果 host 是字串序列,則 TCP 伺服器綁定到序列指定的所有網路介面。

    • +
    • host 是空字串或 None,則所有介面都被假定並回傳多個 socket 的清單(可能一個用於 IPv4,另一個用於 IPv6)。

  • -
  • 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).

  • -
  • family can be set to either socket.AF_INET or -AF_INET6 to force the socket to use IPv4 or IPv6. -If not set, the family will be determined from host name -(defaults to AF_UNSPEC).

  • -
  • flags is a bitmask for getaddrinfo().

  • -
  • sock can optionally be specified in order to use a preexisting -socket object. If specified, host and port must not be specified.

    +
  • 可以設定 port 參數以指定伺服器應該監聽的埠。如果是 0None(預設值),將隨機選擇一個未使用的埠(請注意,如果 host 解析為多個網路介面,將為每個介面隨機選擇不同的隨機埠)。

  • +
  • family 可以設定為 socket.AF_INETAF_INET6 以強制使用 IPv4 或 IPv6。如果未設定,family 將從主機名稱決定(預設為 AF_UNSPEC)。

  • +
  • flagsgetaddrinfo() 的位元遮罩。

  • +
  • 可以可選地指定 sock 以使用現有的 socket 物件。如果指定了,hostport 不能指定。

    備註

    -

    The sock argument transfers ownership of the socket to the -server created. To close the socket, call the server's -close() method.

    +

    sock 引數將 socket 的所有權轉移給建立的伺服器。要關閉 socket,請呼叫伺服器的 close() 方法。

  • -
  • backlog is the maximum number of queued connections passed to -listen() (defaults to 100).

  • -
  • ssl can be set to an SSLContext instance to enable -TLS over the accepted connections.

  • -
  • 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.

  • -
  • 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.

  • -
  • 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).

  • -
  • 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).

  • -
  • 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 Server.start_serving() or -Server.serve_forever() to make the server to start accepting -connections.

  • +
  • backlog 是傳遞給 listen() 的最大佇列連線數(預設為 100)。

  • +
  • ssl 可以設定為 SSLContext 實例以在接受的連線上啟用 TLS。

  • +
  • reuse_address 告訴內核重用 TIME_WAIT 狀態下的本地 socket,而不等待其自然超時過期。如果未指定,在 Unix 上將自動設置為 True

  • +
  • reuse_port 告訴內核允許此端點繫結到與其他現有端點繫結的相同埠,只要它們在建立時都設置了此旗標。此選項在旗標 Windows 上不受支援。

  • +
  • (對於 TLS 伺服器)ssl_handshake_timeout 是在中斷連線之前等待 TLS 握手完成的時間(以秒為單位)。如果為 None(預設),則為 60.0 秒。

  • +
  • ssl_shutdown_timeout 是等待 SSL 關閉完成以前中斷連線的時間,以秒為單位。如果為 None (預設值),則會等待 30.0 秒。

  • +
  • start_serving 設置為 True(預設)將使建立的伺服器立即開始接受連接。當設置為 False 時,用戶應該等待 Server.start_serving()Server.serve_forever() 來使伺服器開始接受連線。

在 3.5 版的變更: 新增 ProactorEventLoop 中的 SSL/TLS 支援。

-

在 3.5.1 版的變更: The host parameter can be a sequence of strings.

+

在 3.5.1 版的變更: host 參數可以是字串序列。

在 3.6 版的變更: 新增 ssl_handshake_timeoutstart_serving 參數。所有 TCP 連線都預設有 socket.TCP_NODELAY socket 選項。

@@ -986,23 +755,16 @@

Creating network serv

也參考

-

The start_server() function is a higher-level alternative API -that returns a pair of StreamReader and StreamWriter -that can be used in an async/await code.

+

start_server() 函式是一個更高階的替代 API,它回傳一對 StreamReaderStreamWriter,可以在 async/await 程式碼中使用。

coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)
-

Similar to loop.create_server() but works with the -AF_UNIX socket family.

-

path is the name of a Unix domain socket, and is required, -unless a sock argument is provided. Abstract Unix sockets, -str, bytes, and Path paths -are supported.

-

See the documentation of the loop.create_server() method -for information about arguments to this method.

+

類似 loop.create_server(),但適用於 AF_UNIX socket 家族。

+

path 是 Unix 域 socket 的名稱,除非提供了 sock 引數,否則必須給定。支援抽象 Unix sockets、strbytesPath 路徑。

+

有關此方法的引數資訊,請參閱 loop.create_server() 方法的文件。

適用:Unix。

@@ -1017,32 +779,22 @@

Creating network serv
coroutine loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)
-

Wrap an already accepted connection into a transport/protocol pair.

-

This method can be used by servers that accept connections outside -of asyncio but that use asyncio to handle them.

+

將已接受的連線包裝成傳輸層/協議對。

+

此方法可以由在 asyncio 外接受連線但使用 asyncio 處理連線的伺服器使用。

參數:

    -
  • protocol_factory must be a callable returning a -protocol implementation.

  • -
  • sock is a preexisting socket object returned from -socket.accept.

    +
  • protocol_factory 必須是可呼叫的函式,回傳 protocol 實作。

  • +
  • sock 是從 socket.accept 回傳的預先存在的 socket 物件。

    備註

    -

    The sock argument transfers ownership of the socket to the -transport created. To close the socket, call the transport's -close() method.

    +

    引數 sock 將 socket 所有權轉移給所建立的傳輸 socket,請呼叫傳輸的 close() 方法。

  • -
  • ssl can be set to an SSLContext to enable SSL over -the accepted connections.

  • -
  • 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).

  • -
  • 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).

  • +
  • ssl 可以設置為 SSLContext 以在已接受的連線上啟用 SSL。

  • +
  • (對於 SSL 連線)ssl_handshake_timeout 是在中斷連線之前等待 SSL 握手完成的時間(以秒為單位)。如果為 None(預設),則為 60.0 秒。

  • +
  • ssl_shutdown_timeout 是等待 SSL 關閉完成以前中斷連線的時間,以秒為單位。如果為 None (預設值),則會等待 30.0 秒。

-

Returns a (transport, protocol) pair.

+

回傳 (transport, protocol) 對。

Added in version 3.5.3.

@@ -1056,25 +808,16 @@

Creating network serv

-

Transferring files

+

傳輸檔案

coroutine loop.sendfile(transport, file, offset=0, count=None, *, fallback=True)
-

Send a file over a transport. Return the total number of bytes -sent.

-

The method uses high-performance os.sendfile() if available.

-

file must be a regular file object opened in binary mode.

-

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 -file.tell() can be used to obtain the actual -number of bytes sent.

-

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).

-

Raise SendfileNotAvailableError if the system does not support -the sendfile syscall and fallback is False.

+

通過 transport 發送 file。回傳發送的總位元組數。

+

如果可用,該方法使用高性能 os.sendfile()

+

file 必須是以二進位模式打開的常規檔案物件。

+

offset 告訴從哪裡開始讀取檔案。如果指定了,count 是要傳輸的總位元組數,而不是發送檔案直到達到 EOF。即使此方法引發錯誤時,檔案位置也始終更新,可以使用 file.tell() 取得實際發送的位元組數。

+

fallback 設置為 True 會使 asyncio 在平台不支援 sendfile 系統呼叫時(例如 Windows 或 Unix 上的 SSL socket)手動讀取和發送檔案。

+

如果系統不支援 sendfile 系統呼叫且 fallbackFalse,則引發 SendfileNotAvailableError

Added in version 3.7.

@@ -1082,36 +825,22 @@

Transferring files
-

TLS Upgrade

+

TLS 升級

coroutine loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)
-

Upgrade an existing transport-based connection to TLS.

-

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.

-

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.

-

In some situations (e.g. when the passed transport is already closing) this -may return None.

+

將基於傳輸的現有連線升級到 TLS。

+

建立 TLS 編解碼器實例並在 transportprotocol 之間插入它。編解碼器既實作了對於 transport 的協議,也實作了對於 protocol 的傳輸。

+

回傳建立的雙介面實例。在 await 後,protocol 必須停止使用原始的 transport,僅與回傳的物件通信,因為編碼器快取了 protocol 端的資料,並且與 transport 間歇性地交換額外的 TLS session 封包。

+

在某些情況下(例如傳入的傳輸已經關閉),此函式可能回傳 None

參數:

    -
  • transport and protocol instances that methods like -create_server() and -create_connection() return.

  • -
  • sslcontext: a configured instance of SSLContext.

  • -
  • server_side pass True when a server-side connection is being -upgraded (like the one created by create_server()).

  • -
  • server_hostname: sets or overrides the host name that the target -server's certificate will be matched against.

  • -
  • 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).

  • -
  • 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).

  • +
  • transportprotocol 實例,由像 create_server()create_connection() 等方法回傳。

  • +
  • sslcontext:配置好的 SSLContext 實例。

  • +
  • 當升級伺服器端連線時(像由 create_server() 建立的那樣)傳遞 True

  • +
  • server_hostname:設置或覆蓋將用於匹配目標伺服器憑證的主機名。

  • +
  • ssl_handshake_timeout (對於 TLS 連線)是等待 TLS 交握的時間,以秒為單位,在那之前若未完成則會中斷連線。如果為 None (預設值),則會等待 60.0 秒。

  • +
  • ssl_shutdown_timeout 是等待 SSL 關閉完成以前中斷連線的時間,以秒為單位。如果為 None (預設值),則會等待 30.0 秒。

Added in version 3.7.

@@ -1123,70 +852,54 @@

TLS Upgrade
-

Watching file descriptors

+

監視檔案描述器

loop.add_reader(fd, callback, *args)
-

Start monitoring the fd file descriptor for read availability and -invoke callback with the specified arguments once fd is available for -reading.

+

開始監視 fd 檔案描述器的讀取可用性,一但 fd 可讀取,使用指定引數呼叫 callback

loop.remove_reader(fd)
-

Stop monitoring the fd file descriptor for read availability. Returns -True if fd was previously being monitored for reads.

+

停止監視 fd 檔案描述器的讀取可用性。如果 fd 之前正在監視讀取,則回傳 True

loop.add_writer(fd, callback, *args)
-

Start monitoring the fd file descriptor for write availability and -invoke callback with the specified arguments once fd is available for -writing.

-

Use functools.partial() to pass keyword arguments to callback.

+

開始監視 fd 檔案描述器的寫入可用性,一旦 fd 可寫入,使用指定引數呼叫 callback

+

使用 functools.partial()callback 傳送關鍵字引數

loop.remove_writer(fd)
-

Stop monitoring the fd file descriptor for write availability. Returns -True if fd was previously being monitored for writes.

+

停止監視 fd 檔案描述器的寫入可用性。如果 fd 之前正在監視寫入,則回傳 True

-

See also Platform Support section -for some limitations of these methods.

+

另請參閱平台支援部分以了解這些方法的一些限制。

-

Working with socket objects directly

-

In general, protocol implementations that use transport-based APIs -such as loop.create_connection() and 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 socket objects directly is more -convenient.

+

直接使用 socket 物件

+

一般情況下,使用基於傳輸的 API(如 loop.create_connection()loop.create_server())的協議實作比直接使用 socket 的實作更快。然而在某些情況下性能不是關鍵,直接使用 socket 物件更方便。

coroutine loop.sock_recv(sock, nbytes)
-

Receive up to nbytes from sock. Asynchronous version of -socket.recv().

-

Return the received data as a bytes object.

-

sock must be a non-blocking socket.

+

sock 接收最多 nbytessocket.recv() 的非同步版本。

+

將接收到的資料作為 bytes 物件回傳。

+

sock 必須是非阻塞 socket。

-

在 3.7 版的變更: Even though this method was always documented as a coroutine -method, releases before Python 3.7 returned a Future. -Since Python 3.7 this is an async def method.

+

在 3.7 版的變更: 儘管此方法一直記錄為協程方法,但 Python 3.7 之前的版本回傳 Future。自 Python 3.7 起,這是 async def 方法。

coroutine loop.sock_recv_into(sock, buf)
-

Receive data from sock into the buf buffer. Modeled after the blocking -socket.recv_into() method.

-

Return the number of bytes written to the buffer.

-

sock must be a non-blocking socket.

+

sock 接收資料到 buf 緩衝區。仿照阻塞 socket.recv_into() 方法。

+

回傳寫入緩衝區位元組的數目。

+

sock 必須是非阻塞 socket。

Added in version 3.7.

@@ -1195,10 +908,9 @@

Working with socket
coroutine loop.sock_recvfrom(sock, bufsize)
-

Receive a datagram of up to bufsize from sock. Asynchronous version of -socket.recvfrom().

-

Return a tuple of (received data, remote address).

-

sock must be a non-blocking socket.

+

sock 接收最多 bufsize 大小的資料單元。socket.recvfrom() 的非同步版本。

+

回傳一個元組 (received data, remote address)。

+

sock 必須是非阻塞 socket。

Added in version 3.11.

@@ -1207,11 +919,9 @@

Working with socket
coroutine loop.sock_recvfrom_into(sock, buf, nbytes=0)
-

Receive a datagram of up to nbytes from sock into buf. -Asynchronous version of -socket.recvfrom_into().

-

Return a tuple of (number of bytes received, remote address).

-

sock must be a non-blocking socket.

+

sock 接收最多 nbytes 大小的資料單元到 bufsocket.recvfrom_into() 的非同步版本。

+

回傳一個元組 (number of bytes received, remote address)。

+

sock 必須是非阻塞 socket。

Added in version 3.11.

@@ -1220,29 +930,20 @@

Working with socket
coroutine loop.sock_sendall(sock, data)
-

Send data to the sock socket. Asynchronous version of -socket.sendall().

-

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.

-

sock must be a non-blocking socket.

+

data 發送到 sock socket。socket.sendall() 的非同步版本。

+

此方法將繼續發送到 socket,直到 data 中的所有資料都已發送或發生錯誤。成功時回傳 None。錯誤時引發例外。此外,沒有辦法確定接收端成功處理了多少資料(如果有的話)。

+

sock 必須是非阻塞 socket。

-

在 3.7 版的變更: Even though the method was always documented as a coroutine -method, before Python 3.7 it returned a Future. -Since Python 3.7, this is an async def method.

+

在 3.7 版的變更: 儘管該方法一直被記錄為協程方法,但在 Python 3.7 之前它回傳 Future。從 Python 3.7 開始,這是一個 async def 方法。

coroutine loop.sock_sendto(sock, data, address)
-

Send a datagram from sock to address. -Asynchronous version of -socket.sendto().

-

Return the number of bytes sent.

-

sock must be a non-blocking socket.

+

sockaddress 發送一個資料單元。socket.sendto() 的非同步版本。

+

回傳發送的位元組數。

+

sock 必須是非阻塞 socket。

Added in version 3.11.

@@ -1251,38 +952,26 @@

Working with socket
coroutine loop.sock_connect(sock, address)
-

Connect sock to a remote socket at address.

-

Asynchronous version of socket.connect().

-

sock must be a non-blocking socket.

+

sock 連線到位於 address 的遠端 socket。

+

socket.connect() 的非同步版本。

+

sock 必須是非阻塞 socket。

-

在 3.5.2 版的變更: address no longer needs to be resolved. sock_connect -will try to check if the address is already resolved by calling -socket.inet_pton(). If not, -loop.getaddrinfo() will be used to resolve the -address.

+

在 3.5.2 版的變更: 不再需要解析 addresssock_connect 將嘗試透過呼叫 socket.inet_pton() 檢查 address 是否已解析。如果沒有,將使用 loop.getaddrinfo() 解析 address

coroutine loop.sock_accept(sock)
-

Accept a connection. Modeled after the blocking -socket.accept() method.

-

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.

-

sock must be a non-blocking socket.

+

接受一個連線。模擬阻塞的 socket.accept() 方法。

+

Socket 必須繫結到一個地址並偵聽連線。回傳值是一個 (conn, address) 對,其中 conn 是一個 socket 物件,可在連線上發送和接收資料,address 是連接另一端對應的 socket 地址。

+

sock 必須是非阻塞 socket。

-

在 3.7 版的變更: Even though the method was always documented as a coroutine -method, before Python 3.7 it returned a Future. -Since Python 3.7, this is an async def method.

+

在 3.7 版的變更: 儘管該方法一直被記錄為協程方法,但在 Python 3.7 之前它回傳 Future。從 Python 3.7 開始,這是一個 async def 方法。

也參考

@@ -1293,24 +982,14 @@

Working with socket
coroutine loop.sock_sendfile(sock, file, offset=0, count=None, *, fallback=True)
-

Send a file using high-performance os.sendfile if possible. -Return the total number of bytes sent.

-

Asynchronous version of socket.sendfile().

-

sock must be a non-blocking socket.SOCK_STREAM -socket.

-

file must be a regular file object open in binary mode.

-

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 -file.tell() can be used to obtain the actual -number of bytes sent.

-

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).

-

Raise SendfileNotAvailableError if the system does not support -sendfile syscall and fallback is False.

-

sock must be a non-blocking socket.

+

如果可行,使用高性能 os.sendfile 發送檔案。回傳發送的總位元組數。

+

socket.sendfile() 的非同步版本。

+

sock 必須是非阻塞的 socket.SOCK_STREAM socket

+

file 必須是以二進位模式打開的常規檔案物件。

+

offset 告訴從哪裡開始讀取檔案。如果指定了,count 是要傳輸的總位元組數,而不是發送檔案直到達到 EOF。即使此方法引發錯誤時,檔案位置也始終更新,可以使用 file.tell() 取得實際發送的位元組數。

+

當設置為 True 時,fallback 使 asyncio 在平台不支援 sendfile 系統呼叫時(例如 Windows 或 Unix 上的 SSL socket)手動讀取和發送檔案。

+

如果系統不支援 sendfile 系統呼叫且 fallbackFalse,引發 SendfileNotAvailableError

+

sock 必須是非阻塞 socket。

Added in version 3.7.

@@ -1322,86 +1001,67 @@

DNS
coroutine loop.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)
-

Asynchronous version of socket.getaddrinfo().

+

socket.getaddrinfo() 的非同步版本。

coroutine loop.getnameinfo(sockaddr, flags=0)
-

Asynchronous version of socket.getnameinfo().

+

socket.getnameinfo() 的非同步版本。

-

在 3.7 版的變更: Both getaddrinfo and getnameinfo methods were always documented -to return a coroutine, but prior to Python 3.7 they were, in fact, -returning asyncio.Future objects. Starting with Python 3.7 -both methods are coroutines.

+

在 3.7 版的變更: getaddrinfogetnameinfo 方法一直被記錄為回傳協程,但在 Python 3.7 之前它們實際上回傳 asyncio.Future 物件。從 Python 3.7 開始,兩個方法都是協程。

-

Working with pipes

+

使用管道

coroutine loop.connect_read_pipe(protocol_factory, pipe)
-

Register the read end of pipe in the event loop.

-

protocol_factory must be a callable returning an -asyncio protocol implementation.

-

pipe is a file-like object.

-

Return pair (transport, protocol), where transport supports -the ReadTransport interface and protocol is an object -instantiated by the protocol_factory.

-

With SelectorEventLoop event loop, the pipe is set to -non-blocking mode.

+

在事件迴圈中註冊 pipe 的讀取端。

+

protocol_factory 必須是一個回傳 asyncio protocol 實作的可呼叫函式。

+

pipe類檔案物件

+

回傳 (transport, protocol) 對,其中 transport 支援 ReadTransport 介面,protocol 是由 protocol_factory 實例化的物件。

+

使用 SelectorEventLoop 事件迴圈時,pipe 設置為非阻塞模式。

coroutine loop.connect_write_pipe(protocol_factory, pipe)
-

Register the write end of pipe in the event loop.

-

protocol_factory must be a callable returning an -asyncio protocol implementation.

-

pipe is file-like object.

-

Return pair (transport, protocol), where transport supports -WriteTransport interface and protocol is an object -instantiated by the protocol_factory.

-

With SelectorEventLoop event loop, the pipe is set to -non-blocking mode.

+

在事件迴圈中註冊 pipe 的寫入端。

+

protocol_factory 必須是一個回傳 asyncio protocol 實作的可呼叫函式。

+

pipefile-like object

+

回傳 (transport, protocol) 對,其中 transport 支援 WriteTransport 介面,protocol 是由 protocol_factory 實例化的物件。

+

使用 SelectorEventLoop 事件迴圈時,pipe 設置為非阻塞模式。

備註

-

SelectorEventLoop does not support the above methods on -Windows. Use ProactorEventLoop instead for Windows.

+

SelectorEventLoop 在 Windows 上不支援上述方法。對於 Windows 請使用 ProactorEventLoop

-

Unix signals

+

Unix 訊號

loop.add_signal_handler(signum, callback, *args)
-

Set callback as the handler for the signum signal.

-

The callback will be invoked by loop, along with other queued callbacks -and runnable coroutines of that event loop. Unlike signal handlers -registered using signal.signal(), a callback registered with this -function is allowed to interact with the event loop.

-

Raise ValueError if the signal number is invalid or uncatchable. -Raise RuntimeError if there is a problem setting up the handler.

-

Use functools.partial() to pass keyword arguments to callback.

-

Like signal.signal(), this function must be invoked in the main -thread.

+

callback 設置為 signum 訊號的處理程式。

+

該回呼將由 loop 呼叫,與該事件迴圈的其他排隊回呼和可運行的協程一起。與使用 signal.signal() 註冊的訊號處理程式不同,使用此函式註冊的回呼允許與事件迴圈進行互動。

+

如果訊號號無效或不可捕獲,引發 ValueError。如果設定處理程序有問題,拋出 RuntimeError

+

使用 functools.partial()callback 傳送關鍵字引數

+

signal.signal() 一樣,此函式必須在主執行緒中呼叫。

loop.remove_signal_handler(sig)
-

Remove the handler for the sig signal.

-

Return True if the signal handler was removed, or False if -no handler was set for the given signal.

+

移除 sig 訊號的處理程式。

+

如果訊號處理程式被移除,回傳 True;如果給定訊號沒有設置處理程式,回傳 False

適用:Unix。

@@ -1409,17 +1069,16 @@

Unix signals

也參考

-

The signal module.

+

signal 模組。

-

Executing code in thread or process pools

+

在執行緒池或行程池中執行程式碼

awaitable loop.run_in_executor(executor, func, *args)
-

Arrange for func to be called in the specified executor.

-

The executor argument should be an concurrent.futures.Executor -instance. The default executor is used if executor is None.

+

安排在指定的執行器中呼叫 func

+

executor 引數應該是 concurrent.futures.Executor 實例。如果 executorNone,則使用預設執行器。

範例:

import asyncio
 import concurrent.futures
@@ -1462,62 +1121,42 @@ 

Executing code in th asyncio.run(main())

-

Note that the entry point guard (if __name__ == '__main__') -is required for option 3 due to the peculiarities of multiprocessing, -which is used by ProcessPoolExecutor. -See Safe importing of main module.

-

This method returns a asyncio.Future object.

-

Use functools.partial() to pass keyword arguments to func.

+

請注意,由於 multiprocessing(由 ProcessPoolExecutor 使用)的特殊性,選項 3 需要進入點保護(if __name__ == '__main__')。請參閱主模組的安全引入

+

此方法回傳 asyncio.Future 物件。

+

使用 functools.partial() 將來關鍵字引數傳遞func

-

在 3.5.3 版的變更: 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 -(ThreadPoolExecutor) to set the -default.

+

在 3.5.3 版的變更: loop.run_in_executor() 不再配置它建立的執行緒池執行器的 max_workers,而是讓執行緒池執行器(ThreadPoolExecutor)設定預設值。

loop.set_default_executor(executor)
-

Set executor as the default executor used by run_in_executor(). -executor must be an instance of -ThreadPoolExecutor.

+

executor 設置為 run_in_executor() 使用的預設執行器。executor 必須是 ThreadPoolExecutor 的實例。

-

在 3.11 版的變更: executor must be an instance of -ThreadPoolExecutor.

+

在 3.11 版的變更: executor 必須是 ThreadPoolExecutor 的實例。

-

Error Handling API

-

Allows customizing how exceptions are handled in the event loop.

+

錯誤處理 API

+

允許自定義事件迴圈中的例外處理方式。

loop.set_exception_handler(handler)
-

Set handler as the new event loop exception handler.

-

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 call_exception_handler() documentation for details -about context).

-

If the handler is called on behalf of a Task or -Handle, it is run in the -contextvars.Context of that task or callback handle.

+

handler 設定為新的事件迴圈例外處理程式。

+

如果 handlerNone,則將設置預設例外處理程式。否則,handler 必須是一個可呼叫物件,簽名匹配 (loop, context),其中 loop 是參照活躍事件迴圈的,context 是包含例外詳細資訊的 dict 物件(有關情境的詳細資訊,請參閱 call_exception_handler() 文件)。

+

如果代表 TaskHandle 呼叫處理程式,它將在該任務或回呼處理程式的 contextvars.Context 中運行。

-

在 3.12 版的變更: The handler may be called in the Context -of the task or handle where the exception originated.

+

在 3.12 版的變更: 處理程式可能在引發例外的任務或處理程式的 Context 中被呼叫。

loop.get_exception_handler()
-

Return the current exception handler, or None if no custom -exception handler was set.

+

回傳當前的例外處理程式,如果未設置自定義例外處理程式,則回傳 None

Added in version 3.5.2.

@@ -1526,211 +1165,150 @@

Error Handling API
loop.default_exception_handler(context)
-

Default exception handler.

-

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.

-

context parameter has the same meaning as in -call_exception_handler().

+

預設例外處理程式。

+

當發生例外且未設置例外處理程式時呼叫此函式。自定義例外處理程式可以呼叫此函式以轉由預設處理程式處理。

+

context 參數與 call_exception_handler() 中的意思相同。

loop.call_exception_handler(context)
-

Call the current event loop exception handler.

-

context is a dict object containing the following keys -(new keys may be introduced in future Python versions):

+

呼叫當前事件迴圈例外處理程式。

+

context 是一個包含以下鍵的 dict 物件(未來的 Python 版本中可能會引入新的鍵):

    -
  • 'message': Error message;

  • -
  • 'exception' (optional): Exception object;

  • -
  • 'future' (optional): asyncio.Future instance;

  • -
  • 'task' (optional): asyncio.Task instance;

  • -
  • 'handle' (optional): asyncio.Handle instance;

  • -
  • 'protocol' (optional): Protocol instance;

  • -
  • 'transport' (optional): Transport instance;

  • -
  • 'socket' (optional): socket.socket instance;

  • +
  • 'message':錯誤訊息;

  • +
  • 'exception'(可選):例外物件;

  • +
  • 'future'(可選): asyncio.Future 實例;

  • +
  • 'task'(可選): asyncio.Task 實例;

  • +
  • 'handle'(可選): asyncio.Handle 實例;

  • +
  • 'protocol'(可選): Protocol 實例;

  • +
  • 'transport'(可選): Transport 實例;

  • +
  • 'socket'(可選): socket.socket 實例;

  • -
    'asyncgen' (optional): Asynchronous generator that caused

    the exception.

    +
    'asyncgen'(可選): 非同步產生器引發

    例外。

備註

-

This method should not be overloaded in subclassed -event loops. For custom exception handling, use -the set_exception_handler() method.

+

此方法不應在子類別事件迴圈中被覆寫。為了自定義例外處理,請使用 set_exception_handler() 方法。

-

Enabling debug mode

+

啟用除錯模式

loop.get_debug()
-

Get the debug mode (bool) of the event loop.

-

The default value is True if the environment variable -PYTHONASYNCIODEBUG is set to a non-empty string, False -otherwise.

+

取得事件迴圈的除錯模式(bool)。

+

如果環境變數 PYTHONASYNCIODEBUG 被設定為非空字串,則預設值為 True,否則為 False

loop.set_debug(enabled: bool)
-

Set the debug mode of the event loop.

+

設定事件迴圈的除錯模式。

-

在 3.7 版的變更: The new Python Development Mode can now also be used -to enable the debug mode.

+

在 3.7 版的變更: 現在也可以使用新的 Python 開發模式 啟用除錯模式。

loop.slow_callback_duration
-

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.

-

Default value is 100 milliseconds.

+

此屬性可用於設定被視為"慢"的最短執行時間(以秒為單位)。啟用偵錯模式後,"慢"回呼將被記錄。

+

預設值為 100 毫秒

-

Running Subprocesses

-

Methods described in this subsections are low-level. In regular -async/await code consider using the high-level -asyncio.create_subprocess_shell() and -asyncio.create_subprocess_exec() convenience functions instead.

+

運行子行程

+

本小節描述的方法是低階的。在常規的 async/await 程式碼中,請考慮使用高階 asyncio.create_subprocess_shell()asyncio.create_subprocess_exec() 輔助功能而不是。

備註

-

On Windows, the default event loop ProactorEventLoop supports -subprocesses, whereas SelectorEventLoop does not. See -Subprocess Support on Windows for -details.

+

在 Windows 上,預設事件迴圈 ProactorEventLoop 支援子行程,而 SelectorEventLoop 不支援。詳細資訊請參見 Windows 上對於子行程的支援

coroutine loop.subprocess_exec(protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
-

Create a subprocess from one or more string arguments specified by -args.

-

args must be a list of strings represented by:

+

args 指定的一個或多個字串引數建立子行程。

+

args 必須是由以下項表示的字串串列:

-

The first string specifies the program executable, -and the remaining strings specify the arguments. Together, string -arguments form the argv of the program.

-

This is similar to the standard library subprocess.Popen -class called with shell=False and the list of strings passed as -the first argument; however, where Popen takes -a single argument which is list of strings, subprocess_exec -takes multiple string arguments.

-

The protocol_factory must be a callable returning a subclass of the -asyncio.SubprocessProtocol class.

+

第一個字串指定程序可執行檔案,其餘字串指定引數。字串引數一起組成程序的 argv

+

這與標準函式庫 subprocess.Popen 類似,使用 shell=False 呼叫並將字串串列作為第一個引數傳遞;然而,Popen 接受單個字串串列引數,subprocess_exec 接受多個字串引數。

+

protocol_factory 必須是回傳 asyncio.SubprocessProtocol 子類別的可呼叫物件。

其他參數:

    -
  • stdin can be any of these:

    +
  • stdin 可以是以下任意一個:

      -
    • a file-like object

    • -
    • an existing file descriptor (a positive integer), for example those created with os.pipe()

    • -
    • the subprocess.PIPE constant (default) which will create a new -pipe and connect it,

    • -
    • the value None which will make the subprocess inherit the file -descriptor from this process

    • -
    • the subprocess.DEVNULL constant which indicates that the -special os.devnull file will be used

    • +
    • 類檔案物件

    • +
    • 現有的檔案描述器(正整數),例如用 os.pipe() 建立的

    • +
    • subprocess.PIPE 常數(預設),它將建立一個新的管道並連線,

    • +
    • None 將使子行程從此行程繼承檔案描述器

    • +
    • subprocess.DEVNULL 常數,表示將使用特殊的 os.devnull 檔案

  • -
  • stdout can be any of these:

    +
  • stdout 可以是以下任意一個:

      -
    • a file-like object

    • -
    • the subprocess.PIPE constant (default) which will create a new -pipe and connect it,

    • -
    • the value None which will make the subprocess inherit the file -descriptor from this process

    • -
    • the subprocess.DEVNULL constant which indicates that the -special os.devnull file will be used

    • +
    • 類檔案物件

    • +
    • subprocess.PIPE 常數(預設),它將建立一個新的管道並連線,

    • +
    • None 將使子行程從此行程繼承檔案描述器

    • +
    • subprocess.DEVNULL 常數,表示將使用特殊的 os.devnull 檔案

  • -
  • stderr can be any of these:

    +
  • stderr 可以是以下任意一個:

      -
    • a file-like object

    • -
    • the subprocess.PIPE constant (default) which will create a new -pipe and connect it,

    • -
    • the value None which will make the subprocess inherit the file -descriptor from this process

    • -
    • the subprocess.DEVNULL constant which indicates that the -special os.devnull file will be used

    • -
    • the subprocess.STDOUT constant which will connect the standard -error stream to the process' standard output stream

    • +
    • 類檔案物件

    • +
    • subprocess.PIPE 常數(預設),它將建立一個新的管道並連線,

    • +
    • None 將使子行程從此行程繼承檔案描述器

    • +
    • subprocess.DEVNULL 常數,表示將使用特殊的 os.devnull 檔案

    • +
    • subprocess.STDOUT 常數,它將標準錯誤串流連線到行程的標準輸出串流

  • -
  • All other keyword arguments are passed to subprocess.Popen -without interpretation, except for bufsize, universal_newlines, -shell, text, encoding and errors, which should not be specified -at all.

    -

    The asyncio subprocess API does not support decoding the streams -as text. bytes.decode() can be used to convert the bytes returned -from the stream to text.

    +
  • 所有其他關鍵字引數都會傳遞給 subprocess.Popen 而不進行直譯,但 bufsizeuniversal_newlinesshelltextencodingerrors 除外,這些不應該指定。

    +

    asyncio 子行程 API 不支援將串流解碼為文本。可以使用 bytes.decode() 將從串流回傳的位元組轉換為文本。

-

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 -connect_write_pipe() or connect_read_pipe() for use -with the event loop.

-

See the constructor of the subprocess.Popen class -for documentation on other arguments.

-

Returns a pair of (transport, protocol), where transport -conforms to the asyncio.SubprocessTransport base class and -protocol is an object instantiated by the protocol_factory.

+

如果傳遞給 stdinstdoutstderr 的類檔案物件表示管道,則該管道的另一端應該使用 connect_write_pipe()connect_read_pipe() 註冊到事件迴圈中。

+

有關其他引數的文件,請參閱 subprocess.Popen 類別的建構函式。

+

回傳 (transport, protocol) 對,其中 transport 符合 asyncio.SubprocessTransport 基底類別,protocol 是由 protocol_factory 實例化的物件。

coroutine loop.subprocess_shell(protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
-

Create a subprocess from cmd, which can be a str or a -bytes string encoded to the -filesystem encoding, -using the platform's "shell" syntax.

-

This is similar to the standard library subprocess.Popen -class called with shell=True.

-

The protocol_factory must be a callable returning a subclass of the -SubprocessProtocol class.

-

See subprocess_exec() for more details about -the remaining arguments.

-

Returns a pair of (transport, protocol), where transport -conforms to the SubprocessTransport base class and -protocol is an object instantiated by the protocol_factory.

+

使用平台的 “shell” 語法從 cmd 建立子行程,cmd 可以是 str 或編碼為 檔案系統編碼bytes 字串。

+

這類似於標準函式庫中的 subprocess.Popen 類別,使用 shell=True 呼叫。

+

protocol_factory 必須是回傳 SubprocessProtocol 子類別的可呼叫物件。

+

有關其餘引數的更多詳細資訊,請參閱 subprocess_exec()

+

回傳一對 (transport, protocol),其中 transport 符合 SubprocessTransport 基底類別,而 protocol 是由 protocol_factory 實例化的物件。

備註

-

It is the application's responsibility to ensure that all whitespace -and special characters are quoted appropriately to avoid shell injection -vulnerabilities. The 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.

+

由應用程式負責確保適當引用所有空白和特殊字元,以避免 shell 注入風險。可以使用 shlex.quote() 函式來正確跳脫用於構建 shell 命令的字串中的空白和特殊字元。

-

Callback Handles

+

回呼處理

class asyncio.Handle
-

A callback wrapper object returned by loop.call_soon(), -loop.call_soon_threadsafe().

+

loop.call_soon()loop.call_soon_threadsafe() 回傳的回呼包裝器。

get_context()
-

Return the contextvars.Context object -associated with the handle.

+

回傳與處理相關聯的 contextvars.Context 物件。

Added in version 3.12.

@@ -1739,14 +1317,13 @@

Callback Handles
cancel()
-

Cancel the callback. If the callback has already been canceled -or executed, this method has no effect.

+

取消回呼。如果回呼已被取消或執行,此方法將不起作用。

cancelled()
-

Return True if the callback was cancelled.

+

如果回呼已被取消,回傳 True

Added in version 3.7.

@@ -1757,15 +1334,13 @@

Callback Handles
class asyncio.TimerHandle
-

A callback wrapper object returned by loop.call_later(), -and loop.call_at().

-

This class is a subclass of Handle.

+

loop.call_later()loop.call_at() 回傳的回呼包裝器。

+

這個類別是 Handle 的子類別。

when()
-

Return a scheduled callback time as float seconds.

-

The time is an absolute timestamp, using the same time -reference as loop.time().

+

回傳預定的回呼時間,以 float 秒為單位。

+

時間是一個絕對的時間戳,使用與 loop.time() 相同的時間參照。

Added in version 3.7.

@@ -1775,18 +1350,13 @@

Callback Handles -

Server Objects

-

Server objects are created by loop.create_server(), -loop.create_unix_server(), start_server(), -and start_unix_server() functions.

-

Do not instantiate the Server class directly.

+

Server 物件

+

Server 物件是由 loop.create_server()loop.create_unix_server()start_server()start_unix_server() 函式所建立。

+

請勿直接實例化 Server 類別。

class asyncio.Server
-

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:

+

Server 物件是非同步情境管理器。當在 async with 陳述中使用時,可以保證在完成 async with 陳述時,Server 物件將會關閉並停止接受新的連線:

-

在 3.11 版的變更: This class was exposed publicly as asyncio.Server in Python 3.9.11, 3.10.3 and 3.11.

+

在 3.11 版的變更: 此類別在 Python 3.9.11、3.10.3 和 3.11 中以 asyncio.Server 的形式被公開。

close()
-

Stop serving: close listening sockets and set the sockets -attribute to None.

-

The sockets that represent existing incoming client connections -are left open.

-

The server is closed asynchronously; use the wait_closed() -coroutine to wait until the server is closed (and no more -connections are active).

+

停止服務:關閉監聽的 sockets 並將 sockets 屬性設為 None

+

代表現有傳入用戶端連線的 sockets 仍然保持開啟。

+

伺服器以非同步方式關閉;使用 wait_close() 協程等待伺服器關閉(不再有活躍連線)。

get_loop()
-

Return the event loop associated with the server object.

+

回傳與伺服器物件關聯的事件迴圈。

Added in version 3.7.

@@ -1825,15 +1391,9 @@

Server Objects
coroutine start_serving()
-

Start accepting connections.

-

This method is idempotent, so it can be called when -the server is already serving.

-

The start_serving keyword-only parameter to -loop.create_server() and -asyncio.start_server() allows creating a Server object -that is not accepting connections initially. In this case -Server.start_serving(), or Server.serve_forever() can be used -to make the Server start accepting connections.

+

開始接受連線。

+

此方法是幂等的,因此可以在伺服器已經運行時呼叫。

+

start_serving 僅限關鍵字參數只能在 loop.create_server()asyncio.start_server() 中使用,允許建立一個最初不接受連線的 Server 物件。在這種情況下,可以使用 Server.start_serving()Server.serve_forever() 來使 Server 開始接受連線。

Added in version 3.7.

@@ -1842,12 +1402,8 @@

Server Objects
coroutine serve_forever()
-

Start accepting connections until the coroutine is cancelled. -Cancellation of serve_forever task causes the server -to be closed.

-

This method can be called if the server is already accepting -connections. Only one serve_forever task can exist per -one Server object.

+

開始接受連線,直到協程被取消。取消 serve_forever 任務會導致伺服器關閉。

+

如果伺服器已經接受連線,則可以呼叫此方法。每個 Server 物件只能存在一個 serve_forever 任務。

範例:

async def client_connected(reader, writer):
     # Communicate with the client with
@@ -1870,7 +1426,7 @@ 

Server Objects
is_serving()
-

Return True if the server is accepting new connections.

+

如果伺服器正在接受新連線,則回傳 True

Added in version 3.7.

@@ -1879,19 +1435,15 @@

Server Objects
coroutine wait_closed()
-

Wait until the close() method completes and all active -connections have finished.

+

等待 close() 方法完成且所有活動連線都已結束。

sockets
-

List of socket-like objects, asyncio.trsock.TransportSocket, which -the server is listening on.

+

伺服器正在監聽的類似 socket 的物件串列,asyncio.trsock.TransportSocket

-

在 3.7 版的變更: 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.

+

在 3.7 版的變更: 在 Python 3.7 之前,Server.sockets 曾經直接回傳內部伺服器 sockets 的串列。在 3.7 中回傳了該串列的副本。

@@ -1899,18 +1451,14 @@

Server Objects -

Event Loop Implementations

-

asyncio ships with two different event loop implementations: -SelectorEventLoop and ProactorEventLoop.

-

By default asyncio is configured to use SelectorEventLoop -on Unix and ProactorEventLoop on Windows.

+

事件迴圈實作

+

asyncio 內附兩個不同的事件迴圈實作:SelectorEventLoopProactorEventLoop

+

預設情況下,asyncio 配置為在 Unix 上使用 SelectorEventLoop,在 Windows 上使用 ProactorEventLoop

class asyncio.SelectorEventLoop
-

An event loop based on the selectors module.

-

Uses the most efficient selector available for the given -platform. It is also possible to manually configure the -exact selector implementation to be used:

+

基於 selectors 模組的事件迴圈。

+

使用特定平台上最有效的 selector。也可以手動配置要使用的確切 selector 實作:

import asyncio
 import selectors
 
@@ -1930,38 +1478,30 @@ 

Server Objects
class asyncio.ProactorEventLoop
-

An event loop for Windows that uses "I/O Completion Ports" (IOCP).

+

用於 Windows 的事件迴圈,使用"I/O 完成埠"(IOCP)。

適用:Windows。

class asyncio.AbstractEventLoop
-

Abstract base class for asyncio-compliant event loops.

-

The Event Loop Methods section lists all -methods that an alternative implementation of AbstractEventLoop -should have defined.

+

為符合 asyncio 標準的事件迴圈的抽象基礎類別。

+

事件迴圈方法 部分列出了替代 AbstractEventLoop 實作應該定義的所有方法。

範例

-

Note that all examples in this section purposefully show how -to use the low-level event loop APIs, such as loop.run_forever() -and loop.call_soon(). Modern asyncio applications rarely -need to be written this way; consider using the high-level functions -like asyncio.run().

+

請注意,本節中的所有範例都 故意 展示如何使用低階事件迴圈 API,如 loop.run_forever()loop.call_soon()。現代 asyncio 應用程式很少需要這種方式撰寫;請考慮使用高階的函式,如 asyncio.run()

-

Hello World with call_soon()

-

An example using the loop.call_soon() method to schedule a -callback. The callback displays "Hello World" and then stops the -event loop:

+

使用 call_soon() 的 Hello World 範例

+

使用 loop.call_soon() 方法排程回呼的範例。回呼會顯示 "Hello World",然後停止事件迴圈:

import asyncio
 
 def hello_world(loop):
@@ -1983,15 +1523,12 @@ 

範例

也參考

-

A similar Hello World -example created with a coroutine and the run() function.

+

使用協程和 run() 函式建立的類似 Hello World 範例。

-

Display the current date with call_later()

-

An example of a callback displaying the current date every second. The -callback uses the loop.call_later() method to reschedule itself -after 5 seconds, and then stops the event loop:

+

使用 call_later() 顯示目前日期

+

一個回呼的範例,每秒顯示目前日期。回呼使用 loop.call_later() 方法在 5 秒後重新排程自己,然後停止事件迴圈:

import asyncio
 import datetime
 
@@ -2017,14 +1554,12 @@ 

範例

也參考

-

A similar current date example -created with a coroutine and the run() function.

+

使用協程和 run() 函式建立的類似 current date 範例。

-

Watch a file descriptor for read events

-

Wait until a file descriptor received some data using the -loop.add_reader() method and then close the event loop:

+

監聽檔案描述器以進行讀取事件

+

使用 loop.add_reader() 方法等待檔案描述器接收到某些資料,然後關閉事件迴圈:

import asyncio
 from socket import socketpair
 
@@ -2062,20 +1597,15 @@ 

範例

也參考

-

Set signal handlers for SIGINT and SIGTERM

-

(This signals example only works on Unix.)

-

Register handlers for signals SIGINT and SIGTERM -using the loop.add_signal_handler() method:

+

設定 SIGINT 和 SIGTERM 的訊號處理程式

+

(此 signals 範例僅在 Unix 上運作。)

+

使用 loop.add_signal_handler() 方法註冊訊號 SIGINTSIGTERM 的處理程式:

import asyncio
 import functools
 import os
@@ -2115,35 +1645,35 @@ 

範例

目錄

下個主題

Event Loop

+ title="下一章">事件迴圈

此頁面

@@ -374,7 +374,7 @@

瀏覽

模組 |