asyncio
--- 非同步 I/O¶
asyncio 是讓使用者以 async/await 語法來編寫並行 (concurrent) 程式碼的函式庫 (library)。
asyncio 作為多個 Python 非同步框架的基礎,在高效能網路與網頁伺服器、資料庫連線函式庫、分散式任務佇列等服務都可以看得到它。
asyncio 往往是個建構 IO 密集型與高階層結構化網路程式碼的完美選擇。
asyncio 提供了一系列高階 API:
並行地運行 Python 協程 (coroutine) 並擁有完整控制權;
執行網路 IO 與 IPC;
透過佇列 (queue) 分配任務;
同步並行程式碼;
此外,還有一些給函式庫與框架 (framework) 開發者的低階 API:
建立與管理 event loops(事件迴圈),它提供了能被用於
網路
、執行子行程
、處理作業系統訊號
等任務的非同步 API;使用 transports(asyncio 底層傳輸相關類別)來實作高效能協定;
透過 async/await 語法來橋接基於回呼 (callback-based) 的函式庫與程式碼。
You can experiment with an asyncio
concurrent context in the REPL:
$ python -m asyncio
asyncio REPL ...
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
'hello'
Availability: not Emscripten, not WASI.
This module does not work or is not available on WebAssembly platforms
wasm32-emscripten
and wasm32-wasi
. See
WebAssembly 平台 for more information.
參閱
指南與教學
備註
asyncio 的原始碼可以在 Lib/asyncio/ 中找到。