Skip to content

官方资料与延伸阅读 ​

本教程主要参考下面资料。内容以 Python 3.14.5 稳定文档为主,也补充了 Python 3.15 开发文档里已经写明的变化方向。

Python 官方文档 ​

资料用途
asyncio 总览确认 asyncio 适合做什么,以及哪些 API 更常用
A Conceptual Overview of asyncio分清 event loop、coroutine、Task、Future、await 各自负责什么
Runners理解 asyncio.run()、Runner、loop 生命周期和 Python 3.14 变化
Coroutines and Tasks查 Task、TaskGroup、gather、timeout、shield 和取消规则
Event Loop查 loop 低层 API、callback、timer、Future/Task 创建、I/O 方法
Streams查 StreamReader、StreamWriter、drain()、TCP server/client
Queues查 Queue、PriorityQueue、LifoQueue、Python 3.13 的 shutdown
Synchronization Primitives查 Lock、Event、Condition、Semaphore、Barrier
Developing with asyncio查 debug 模式、线程边界、阻塞调用、未等待 coroutine 等排错内容
Transports and Protocols理解 Streams 下面那套 callback 风格的网络接口
High-level API Index快速查高层 API
Low-level API Index快速查低层 API

CPython 源码 ​

资料用途
CPython Lib/asyncio查看 asyncio 标准库源码目录
runners.pyasyncio.run() 和 Runner
base_events.pyBaseEventLoop 和 _run_once
tasks.pyTask、gather、sleep
futures.pyFuture
queues.pyQueue
streams.pyStreams
taskgroups.pyTaskGroup

版本提示 ​

  • 本教程 Demo 按 Python 3.12+ 来写。
  • TaskGroup 和 asyncio.timeout() 从 Python 3.11 开始可用。
  • Python 3.13 为 asyncio.Queue 增加了 shutdown 相关功能。
  • Python 3.14 文档记录了 asyncio.run() 和 Runner.run() 可以接受任意 awaitable。
  • Python 3.15 开发文档提示 asyncio policy system 已弃用并计划在 Python 3.16 移除。教程中因此倾向讲 get_running_loop() 和显式 loop_factory 的方向。

继续怎么读 ​

别一口气读完整源码。按任务走:

  1. 读 asyncio.run() 到 run_until_complete()。
  2. 读 asyncio.sleep() 如何使用 timer Future。
  3. 读 Task 如何让 coroutine 继续执行。
  4. 读 Queue.get() 和 Queue.put() 如何用 Future 唤醒等待者。
  5. 读 Streams 如何把 Protocol callback 转成 awaitable reader/writer。
  6. 再看 TaskGroup 如何处理取消和异常聚合。

面向学习目的的 Python asyncio 中文教程与 mini_asyncio 教学运行时。