KBEngine 内嵌 Python 3.7 asyncio 异步编程指南:协程、任务、流与事件循环全解析
KBEngine 内嵌 Python 3.7 asyncio 异步编程指南:协程、任务、流与事件循环全解析
导读
asyncio 是 Python 标准库中用于编写并发代码的库,核心语法为 async/await。KBEngine 仓库内嵌了完整的 CPython 3.7.3 运行环境(见 kbe/src/lib/python/Include/patchlevel.h 中的 PY_VERSION "3.7.3"),其 asyncio 官方文档 与 Lib/asyncio 源码 一并随仓库提供,是服务器侧 Python 脚本可用的标准异步库。本文将以此文档为主体,结合仓库内 Lib/asyncio 的真实实现,系统讲解 asyncio 的高层 API(协程与任务、流、同步原语、子进程、队列)与底层 API(Future、事件循环、异常),让你能直接基于仓库内嵌的 Python 编写可运行的异步网络、并发任务与超时控制代码。
asyncio 概述:并发代码的标准库
asyncio 是一个使用 async/await 语法编写并发代码的库,常被用作多个 Python 异步框架的基础,这些框架提供了高性能网络服务器、数据库连接库、分布式任务队列等能力。对于 IO 密集型和高层级结构化的网络代码,asyncio 通常是理想选择。
asyncio 提供了一组高层级 API,用于:
- 并发地运行 Python 协程并完全控制其执行;
- 执行网络 IO 和 IPC;
- 控制子进程;
- 通过队列分发任务;
- 同步并发代码。
此外,还为库和框架开发者提供了低层级 API,用于:
- 创建和管理事件循环,提供异步网络、运行子进程、处理 OS 信号等 API;
- 通过 transports 和 protocols 实现高效的协议;
- 桥接基于回调的库与 async/await 语法。
文档开头给出了最小 Hello World 示例(见 asyncio.rst):
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
# Python 3.7+
asyncio.run(main())
仓库中的 asyncio:随内嵌 CPython 3.7.3 提供的标准库
KBEngine 在 kbe/src/lib/python 下内嵌了完整 CPython 源码树:
- 标准库文档位于 kbe/src/lib/python/Doc/library,其中 asyncio 总览为 asyncio.rst,其余章节(协程任务、流、同步、子进程、队列、异常、事件循环、Future、协议等)以独立文档并列存在;
- 标准库实现位于 kbe/src/lib/python/Lib/asyncio,包含
__init__.py、base_events.py、base_tasks.py、coroutines.py、events.py、futures.py、locks.py、protocols.py、queues.py、runners.py、streams.py、subprocess.py、tasks.py、transports.py、selector_events.py、proactor_events.py、unix_events.py、windows_events.py等 24 个模块; - 对应的标准库测试位于 kbe/src/lib/python/Lib/test/test_asyncio,覆盖事件循环、Future、锁、队列、流、SSL、Proactor、Selector 等场景。
这意味着文档描述的所有能力都能在仓库内直接对照源码验证。以下各节按官方文档的章节组织,先讲高层 API,再讲底层 API。
协程与任务(Coroutines and Tasks)
这是 asyncio 应用的入口级章节,文档位于 asyncio-task.rst。
协程:async/await 定义的可等待对象
用 async/await 语法声明的协程是编写 asyncio 应用的首选方式。下面的代码打印 "hello",等待 1 秒,然后打印 "world":
>>> import asyncio
>>> async def main():
... print('hello')
... await asyncio.sleep(1)
... print('world')
>>> asyncio.run(main())
hello
world
注意:仅仅调用协程并不会调度它执行,调用 main() 只会返回一个 <coroutine object main at ...> 对象。文档区分两个紧密相关的概念:
- 协程函数(coroutine function):
async def定义的函数; - 协程对象(coroutine object):调用协程函数返回的对象。
三种运行协程的机制
-
asyncio.run():运行顶层入口main()协程。它负责管理事件循环并收尾异步生成器;不能在同一个线程中已有其他事件循环运行时调用;debug=True时事件循环以调试模式运行;每次调用都会创建新的事件循环并在结束时关闭,应作为 asyncio 程序的唯一入口,理想情况下只调用一次。 -
await 一个协程。以下代码先打印 "hello"(等待 1 秒),再打印 "world"(再等待 2 秒),总计约 3 秒:
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
asyncio.create_task():将协程包装成 asyncioTask并并发执行。将上面示例改为并发后,两个say_after协程同时开始,总耗时约 2 秒(比串行快 1 秒):
async def main():
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
print(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
可等待对象(Awaitables)
能在 await 表达式中使用的对象称为可等待对象,asyncio 中主要有三种:协程、Task、Future。
- 协程:Python 协程本身是可等待的,能被其他协程
await。注意未被 await 的协程对象“根本不会运行”:
import asyncio
async def nested():
return 42
async def main():
# Nothing happens if we just call "nested()".
nested()
# Let's do it differently now and await it:
print(await nested()) # will print "42".
asyncio.run(main())
- Task:用于并发调度协程。用
create_task包装协程后,它会自动被调度“尽快运行”,并且可以被cancel()取消,或通过await等待其完成。 - Future:特殊的底层可等待对象,表示异步操作的最终结果。Future 被 await 时,协程会一直等待,直到 Future 在别处被解析。Future 存在的意义是让基于回调的代码能融入 async/await 语法;应用层代码通常无需创建 Future。一个典型返回 Future 的低层函数是
loop.run_in_executor。
创建任务与睡眠
asyncio.create_task(coro):将协程包装为Task并调度执行,返回 Task 对象。Task 在get_running_loop()返回的循环中执行;若当前线程没有运行中的循环则抛出RuntimeError。该函数是 Python 3.7 新增,3.7 之前应使用底层asyncio.ensure_future():
# In Python 3.7+
task = asyncio.create_task(coro())
# This works in all Python versions but is less readable
task = asyncio.ensure_future(coro())
asyncio.sleep(delay, result=None):阻塞delay秒。如果提供了result,协程完成时将其返回给调用者。sleep()总是挂起当前任务,让其他任务有机会运行。示例:每秒显示一次当前日期,持续 5 秒:
import asyncio
import datetime
async def display_date():
loop = asyncio.get_running_loop()
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
await asyncio.sleep(1)
asyncio.run(display_date())
并发运行:gather
asyncio.gather(*aws, return_exceptions=False) 并发运行 aws 序列中的可等待对象。要点:
- 若
aws中某个元素是协程,会被自动调度为 Task; - 全部成功时,返回聚合结果列表,顺序与
aws中的顺序一致; return_exceptions=False(默认):第一个抛出的异常立即传播给 awaitgather()的任务,其他可等待对象不会被取消,继续运行;return_exceptions=True:异常与成功结果同等对待,聚合进结果列表;- 若
gather()本身被取消,所有尚未完成的提交对象也全部被取消; - 若
aws中某个 Task/Future 被取消,视为抛出了CancelledError,此时gather()本身不会被取消,以防止单个任务取消牵连其他任务。
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
asyncio.run(main())
屏蔽取消:shield
asyncio.shield(aw) 保护可等待对象不被 Task.cancel() 取消。若 aw 是协程会被自动调度为 Task。语义对比:
res = await shield(something())
# 等价于
res = await something()
区别在于:如果包含 shield() 的协程被取消,运行 something() 的 Task 不会被取消;但从 something() 的角度看取消并未发生,不过调用方仍然被取消,所以 await 表达式仍会抛出 CancelledError。若想完全忽略取消(不推荐),需要配合 try/except:
try:
res = await shield(something())
except CancelledError:
res = None
超时:wait_for
asyncio.wait_for(aw, timeout) 带超时等待 aw 完成。timeout 可为 None(阻塞直到完成)或秒数(int/float)。超时发生时,它取消任务并抛出 asyncio.TimeoutError。为避免任务被取消,可用 shield 包装。函数会等到 Future 真正被取消,所以总等待时间可能超过 timeout。若等待本身被取消,aw 也会被取消。
async def eternity():
# Sleep for one hour
await asyncio.sleep(3600)
print('yay!')
async def main():
# Wait for at most 1 second
try:
await asyncio.wait_for(eternity(), timeout=1.0)
except asyncio.TimeoutError:
print('timeout!')
asyncio.run(main())
# Expected output:
# timeout!
等待原语:wait 与 as_completed
asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED) 并发运行 aws 集合中的可等待对象并阻塞,直到满足 return_when 条件,返回 (done, pending) 两个 Task/Future 集合。return_when 可取以下常量:
| 常量 | 说明 |
|---|---|
FIRST_COMPLETED |
任一 future 完成或被取消时返回 |
FIRST_EXCEPTION |
任一 future 因抛异常而完成时返回;若无异常则等价于 ALL_COMPLETED |
ALL_COMPLETED |
所有 future 完成或被取消时返回 |
注意:wait() 不会像 wait_for 那样在超时时取消 future;它不抛 TimeoutError,未完成的 future 只是出现在 pending 集合中。还有一个重要陷阱:wait() 会自动把协程调度为 Task 并返回隐式创建的 Task 对象,因此直接对协程对象做集合成员判断会失效:
# 下面这段代码永远不会走 if 分支:
async def foo():
return 42
coro = foo()
done, pending = await asyncio.wait({coro})
if coro in done: # This branch will never be run!
...
# 正确写法:先 create_task 再 wait
task = asyncio.create_task(foo())
done, pending = await asyncio.wait({task})
if task in done: # Everything will work as expected now.
...
直接向 wait() 传协程对象已被弃用。
asyncio.as_completed(aws, *, timeout=None) 并发运行集合中的可等待对象,返回一个 Future 迭代器,每个 Future 代表剩余可等待对象中最早产生的结果;若超时前未完成所有 Future 则抛 TimeoutError:
for f in as_completed(aws):
earliest_result = await f
# ...
跨线程调度:run_coroutine_threadsafe
asyncio.run_coroutine_threadsafe(coro, loop) 将协程提交到指定事件循环,线程安全,返回一个 concurrent.futures.Future 用于在另一 OS 线程中等待结果。注意:与多数 asyncio 函数不同,它必须显式传 loop 参数。该函数从 Python 3.5.1 起可用。
# Create a coroutine
coro = asyncio.sleep(1, result=3)
# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)
# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
try:
result = future.result(timeout)
except asyncio.TimeoutError:
print('The coroutine took too long, cancelling the task...')
future.cancel()
except Exception as exc:
print(f'The coroutine raised an exception: {exc!r}')
else:
print(f'The coroutine returned: {result!r}')
内省:current_task 与 all_tasks
asyncio.current_task(loop=None):返回当前正在运行的Task实例;没有任务运行时返回None。loop为None时用get_running_loop()获取当前循环(Python 3.7 新增)。asyncio.all_tasks(loop=None):返回事件循环中所有尚未完成的Task对象集合(Python 3.7 新增)。
Task 对象
asyncio.Task 是一个 Future 风格的、运行 Python 协程的对象,非线程安全。事件循环采用协作式调度:循环一次运行一个 Task;当 Task 在等待某个 Future 完成时,事件循环会运行其他 Task、回调或执行 IO。创建 Task 应使用高层 asyncio.create_task() 或底层 loop.create_task()、ensure_future(),不推荐手动实例化。
Task 继承 Future 除 set_result、set_exception 外的全部 API,并支持 contextvars 模块(创建 Task 时复制当前上下文,之后在其副本中运行协程)。
核心方法:
cancel():请求取消 Task,会在事件循环下一轮把CancelledError抛入被包装的协程。协程可以用try ... except CancelledError ... finally清理甚至拒绝取消。因此不同于Future.cancel(),Task.cancel()不保证 Task 一定被取消(虽然完全抑制取消不常见且被明确不鼓励)。拦截取消请求的示例:
async def cancel_me():
print('cancel_me(): before sleep')
try:
# Wait for 1 hour
await asyncio.sleep(3600)
except asyncio.CancelledError:
print('cancel_me(): cancel sleep')
raise
finally:
print('cancel_me(): after sleep')
async def main():
# Create a "cancel_me" Task
task = asyncio.create_task(cancel_me())
# Wait for 1 second
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main(): cancel_me is cancelled now")
asyncio.run(main())
# Expected output:
# cancel_me(): before sleep
# cancel_me(): cancel sleep
# cancel_me(): after sleep
# main(): cancel_me is cancelled now
cancelled():返回 Task 是否已被取消(即请求了 cancel 且被包装协程传播了CancelledError)。done():返回 Task 是否完成(协程返回值、抛异常或被取消)。result():返回协程结果;被取消时抛CancelledError;结果未就绪时抛InvalidStateError。exception():返回协程抛出的异常;正常返回时返回None;被取消时抛CancelledError;未完成时抛InvalidStateError。add_done_callback(callback, *, context=None)/remove_done_callback(callback):注册/移除完成回调,仅供低层回调式代码使用。get_stack(*, limit=None)/print_stack(*, limit=None, file=None):获取/打印 Task 的栈帧或 traceback,便于调试挂起的协程。- 类方法
Task.all_tasks()、Task.current_task()已弃用(将于 Python 3.9 移除),改用模块级asyncio.all_tasks、asyncio.current_task。
基于生成器的旧式协程(已弃用)
支持基于生成器的协程是弃用的(计划 Python 3.10 移除)。它们在 async/await 语法之前出现,用 yield from 表达式 await Future 和其他协程,应使用 @asyncio.coroutine 装饰器标记(虽不强制):
@asyncio.coroutine
def old_style_coroutine():
yield from asyncio.sleep(1)
async def main():
await old_style_coroutine()
相关判断函数:asyncio.iscoroutine(obj) 与 inspect.iscoroutine 不同,它对基于生成器的协程也返回 True;asyncio.iscoroutinefunction(func) 同理。
流(Streams):高层的网络 IO 原语
文档位于 asyncio-stream.rst。Streams 是高层级、async/await 就绪的网络连接原语,发送和接收数据无需回调或低层的 protocols/transports。
顶层流函数
asyncio.open_connection(host=None, port=None, *, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None):建立网络连接,返回(reader, writer),分别为StreamReader和StreamWriter实例。limit决定StreamReader的缓冲区大小上限,默认 64 KiB;其余参数直接传给loop.create_connection。ssl_handshake_timeout参数 Python 3.7 新增。asyncio.start_server(client_connected_cb, host=None, port=None, *, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True):启动 socket 服务器。client_connected_cb在每次新客户端连接建立时被调用,接收(reader, writer)两个参数;它可以是普通可调用对象或协程函数——若是协程函数会自动调度为 Task。limit默认 64 KiB;其余参数传给loop.create_server。- Unix 域套接字变体:
open_unix_connection(path=None, ...)与start_unix_server(client_connected_cb, path=None, ...),仅 Unix 平台可用。
StreamReader
StreamReader 提供从 IO 流读取数据的 API,不建议直接实例化,应通过 open_connection/start_server 获取:
read(n=-1):最多读n字节;n为-1或不提供时读到 EOF 并返回全部字节;收到 EOF 且内部缓冲区为空时返回空bytes。readline():读取一行(以\n结尾的字节序列);EOF 时未找到\n返回部分数据;缓冲区为空返回空bytes。readexactly(n):精确读取n字节;EOF 提前到达则抛IncompleteReadError(可用partial属性拿到已读部分)。readuntil(separator=b'\n'):读到分隔符为止,成功时数据与分隔符从内部缓冲区移除,返回的数据包含末尾分隔符;数据量超过流限制抛LimitOverrunError(数据保留在缓冲区可重读);EOF 提前到达抛IncompleteReadError(partial可能含分隔符的一部分)。at_eof():缓冲区为空且已调用feed_eof时返回True。
StreamWriter
StreamWriter 提供写入 API,同样不建议直接实例化:
write(data)/writelines(data):写入数据,不受流量控制,调用后应接drain()。drain():等待适合继续写入的时机。这是与底层 IO 写缓冲区交互的流量控制方法:当缓冲区达到高水位线时drain()阻塞,直到缓冲区被排空到低水位线以下再恢复写入;无可等待内容时立即返回。典型用法:
writer.write(data)
await writer.drain()
close():关闭流;is_closing():返回流是否已关闭或正在关闭(Python 3.7 新增);wait_closed():等待流关闭,应在close()之后调用(Python 3.7 新增)。write_eof():在缓冲写入数据排空后关闭流的写端;can_write_eof():底层 transport 是否支持write_eof。transport:返回底层 asyncio transport;get_extra_info(name, default=None):访问可选 transport 信息(如'peername')。
实战示例
TCP echo 客户端(使用 asyncio.open_connection):
import asyncio
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
print(f'Send: {message!r}')
writer.write(message.encode())
data = await reader.read(100)
print(f'Received: {data.decode()!r}')
print('Close the connection')
writer.close()
await writer.wait_closed()
asyncio.run(tcp_echo_client('Hello World!'))
TCP echo 服务器(使用 asyncio.start_server):
import asyncio
async def handle_echo(reader, writer):
data = await reader.read(100)
message = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {message!r} from {addr!r}")
print(f"Send: {message!r}")
writer.write(data)
await writer.drain()
print("Close the connection")
writer.close()
async def main():
server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main())
获取 HTTP 头(演示 readline 与 SSL 连接):
import asyncio
import urllib.parse
import sys
async def print_http_headers(url):
url = urllib.parse.urlsplit(url)
if url.scheme == 'https':
reader, writer = await asyncio.open_connection(url.hostname, 443, ssl=True)
else:
reader, writer = await asyncio.open_connection(url.hostname, 80)
query = (
f"HEAD {url.path or '/'} HTTP/1.0\r\n"
f"Host: {url.hostname}\r\n"
f"\r\n"
)
writer.write(query.encode('latin-1'))
while True:
line = await reader.readline()
if not line:
break
line = line.decode('latin1').rstrip()
if line:
print(f'HTTP header> {line}')
# Ignore the body, close the socket
writer.close()
url = sys.argv[1]
asyncio.run(print_http_headers(url))
用法:python example.py http://example.com/path/page.html 或 python example.py https://example.com/path/page.html。
把已打开的 socket 注册为流等待数据(演示 open_connection(sock=...) 与 loop.call_soon 配合):
import asyncio
import socket
async def wait_for_data():
# Get a reference to the current event loop because
# we want to access low-level APIs.
loop = asyncio.get_running_loop()
# Create a pair of connected sockets.
rsock, wsock = socket.socketpair()
# Register the open socket to wait for data.
reader, writer = await asyncio.open_connection(sock=rsock)
# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())
# Wait for data
data = await reader.read(100)
# Got data, we are done: close the socket
print("Received:", data.decode())
writer.close()
# Close the second socket
wsock.close()
asyncio.run(wait_for_data())
同步原语(Synchronization Primitives)
文档位于 asyncio-sync.rst。asyncio 同步原语与 threading 模块类似,但有两条重要差异:
- asyncio 原语非线程安全,不能用于 OS 线程同步(线程同步请用
threading); - 原语方法不接受
timeout参数,需要超时操作时用asyncio.wait_for包裹。
基本原语包括:Lock、Event、Condition、Semaphore、BoundedSemaphore。仓库实现位于 kbe/src/lib/python/Lib/asyncio/locks.py,并有对应测试 test_locks.py。
Lock(互斥锁)
为 asyncio 任务实现互斥锁,保证对共享资源的独占访问。推荐用 async with:
lock = asyncio.Lock()
# ... later
async with lock:
# access shared state
等价于:
await lock.acquire()
try:
# access shared state
finally:
lock.release()
方法:acquire()(等待锁解锁、置为锁定并返回 True)、release()(解锁;对未锁定的锁调用抛 RuntimeError)、locked()(返回是否锁定)。
Event(事件)
用于通知多个 asyncio 任务“某个事件已发生”。内部维护一个标志:set() 置为 true,clear() 重置为 false,wait() 阻塞直到标志为 true,标志初始为 false。示例:
async def waiter(event):
print('waiting for it ...')
await event.wait()
print('... got it!')
async def main():
# Create an Event object.
event = asyncio.Event()
# Spawn a Task to wait until 'event' is set.
waiter_task = asyncio.create_task(waiter(event))
# Sleep for 1 second and set the event.
await asyncio.sleep(1)
event.set()
# Wait until the waiter task is finished.
await waiter_task
asyncio.run(main())
方法:wait()、set()(所有等待任务立即被唤醒)、clear()、is_set()。
Condition(条件变量)
任务用它等待某个事件发生,然后获得共享资源的独占访问。本质上 Condition 结合了 Event 与 Lock 的功能;多个 Condition 可以共享同一个 Lock。可选 lock 参数必须是 Lock 对象或 None(后者自动创建新 Lock)。推荐用法:
cond = asyncio.Condition()
# ... later
async with cond:
await cond.wait()
方法:acquire()、release()、locked()、notify(n=1)(最多唤醒 n 个等待任务,须持有锁)、notify_all()(唤醒全部等待任务,须持有锁)、wait()(释放锁并阻塞直到被 notify 唤醒,随后重新获取锁并返回 True)、wait_for(predicate)(等待谓词为 true,谓词必须是可调用对象,其结果的布尔值即为返回值)。
Semaphore(信号量)与 BoundedSemaphore(有界信号量)
信号量维护内部计数器,每次 acquire() 减一、每次 release() 加一,计数器不能低于零;acquire() 发现为零时阻塞等待。value 默认 1,为负则抛 ValueError。推荐用法:
sem = asyncio.Semaphore(10)
# ... later
async with sem:
# work with shared resource
BoundedSemaphore 是 Semaphore 的变体:如果 release() 使内部计数器超过初始 value 则抛 ValueError。另外注意:Semaphore 允许 release() 调用次数多于 acquire();Python 3.7 起 await lock / with await lock 的旧式获取方式已弃用,应使用 async with lock。
子进程(Subprocesses)
文档位于 asyncio-subprocess.rst。典型示例:运行 shell 命令并获取结果:
import asyncio
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
asyncio.run(run('ls /zzz'))
输出类似:
['ls /zzz' exited with 1]
[stderr]
ls: /zzz: No such file or directory
因为所有子进程函数都是异步的,可以轻松并行运行多个子进程:
async def main():
await asyncio.gather(
run('ls /zzz'),
run('sleep 1; echo "hello"'))
asyncio.run(main())
创建子进程
asyncio.create_subprocess_exec(*args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds):创建子进程(直接执行程序,不经 shell),返回asyncio.subprocess.Process实例。limit设置Process.stdout/stderr的StreamReader包装缓冲区上限(当传入subprocess.PIPE时)。其余参数见loop.subprocess_exec。asyncio.create_subprocess_shell(cmd, ...):运行cmdshell 命令,同样返回Process实例。
安全提示:使用 shell 时必须自行确保所有空白和特殊字符被正确引用以避免shell 注入漏洞,可用 shlex.quote 函数转义。
平台注意:Windows 上默认事件循环实现不支持子进程;Windows 下需使用 ProactorEventLoop 才能使用子进程。
常量
asyncio.subprocess.PIPE:可传给stdin/stdout/stderr。传给stdin时Process.stdin是StreamWriter;传给stdout/stderr时Process.stdout/stderr是StreamReader。asyncio.subprocess.STDOUT:作为stderr参数的特殊值,表示标准错误重定向到标准输出。asyncio.subprocess.DEVNULL:表示使用os.devnull特殊文件。
Process 对象:与子进程交互
Process 包装由上面两个函数创建的 OS 进程,API 与 subprocess.Popen 类似但有明显差异:
- 没有与
Popen.poll()等价的同步轮询方法; communicate()与wait()没有timeout参数,需用wait_for包裹;Process.wait()是异步的,而subprocess.Popen.wait()是阻塞忙循环;- 不支持
universal_newlines参数。
核心方法/属性:
wait():等待子进程终止,设置并返回returncode。注意:使用stdout=PIPE或stderr=PIPE且子进程输出量很大时可能死锁(子进程阻塞等待 OS 管道缓冲区),应改用communicate()。communicate(input=None):与进程交互——把input(bytes)写入stdin,从stdout/stderr读到 EOF,再等待进程终止,返回(stdout_data, stderr_data)元组。写入 stdin 时若进程已提前退出,BrokenPipeError/ConnectionResetError会被忽略。注意数据在内存中缓冲,不适合大或无限的数据量。send_signal(signal):向子进程发送信号(Windows 上SIGTERM是terminate()的别名)。terminate():停止子进程(POSIX 发SIGTERM;Windows 调 Win32TerminateProcess)。kill():杀死子进程(POSIX 发SIGKILL;Windows 是terminate()别名)。stdin/stdout/stderr:分别是StreamWriter/StreamReader或None(未用 PIPE 创建时)。警告:优先用communicate()而非直接操作这些流,以免流暂停读写而阻塞子进程导致死锁。pid:进程 PID(create_subprocess_shell创建的是 shell 的 PID)。returncode:退出码;None表示尚未终止;POSIX 下负值-N表示被信号N终止。
子进程与线程
标准事件循环支持从不同线程运行子进程,但有局限:事件循环必须运行在主线程;从其他线程执行子进程前,须先在主线程调用 get_child_watcher() 实例化 child watcher。其他事件循环实现可能不受这些限制。
示例:读取子进程输出
import asyncio
import sys
async def get_date():
code = 'import datetime; print(datetime.datetime.now())'
# Create the subprocess; redirect the standard output into a pipe.
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdout=asyncio.subprocess.PIPE)
# Read one line of output.
data = await proc.stdout.readline()
line = data.decode('ascii').rstrip()
# Wait for the subprocess exit.
await proc.wait()
return line
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
date = asyncio.run(get_date())
print(f"Current date: {date}")
队列(Queues):任务分发
文档位于 asyncio-queue.rst。asyncio 队列与 queue 模块相似,但非线程安全,专用于 async/await 代码。注意:asyncio 队列方法没有 timeout 参数,带超时的队列操作需用 asyncio.wait_for 包装。
Queue(FIFO 队列)
asyncio.Queue(maxsize=0):先进先出队列。maxsize <= 0 时队列无限大;maxsize > 0 时队列满则 await put() 阻塞,直到 get() 移除一项。与 threading 的 queue 不同,队列大小始终可知,可通过 qsize() 返回。
方法:
maxsize:队列允许的项目数。empty()/full():是否空/满。maxsize=0时full()永不返回True。get():移除并返回一个项目;队列空时等待直到有项目可用。get_nowait():立即可用则返回项目,否则抛QueueEmpty。put(item):放入项目;队列满时等待空位。put_nowait(item):不阻塞放入;无空位则抛QueueFull。join():阻塞直到队列中所有项目都被取出并处理完。未完成任务计数在有项目加入时增加,消费者调用task_done()时减少;计数降为零时join()解除阻塞。task_done():表示此前入队的一个任务已处理完成。每次get()取任务后应调用一次task_done();调用次数多于入队项目数会抛ValueError。
PriorityQueue 与 LifoQueue
asyncio.PriorityQueue:按优先级顺序取出(最小优先),条目通常是(priority_number, data)元组。asyncio.LifoQueue:后进先出(最近添加的最先取出)。
异常
QueueEmpty:对空队列调用get_nowait()时抛出。QueueFull:对已达maxsize的队列调用put_nowait()时抛出。
示例:在多个并发任务间分发负载
import asyncio
import random
import time
async def worker(name, queue):
while True:
# Get a "work item" out of the queue.
sleep_for = await queue.get()
# Sleep for the "sleep_for" seconds.
await asyncio.sleep(sleep_for)
# Notify the queue that the "work item" has been processed.
queue.task_done()
print(f'{name} has slept for {sleep_for:.2f} seconds')
async def main():
# Create a queue that we will use to store our "workload".
queue = asyncio.Queue()
# Generate random timings and put them into the queue.
total_sleep_time = 0
for _ in range(20):
sleep_for = random.uniform(0.05, 1.0)
total_sleep_time += sleep_for
queue.put_nowait(sleep_for)
# Create three worker tasks to process the queue concurrently.
tasks = []
for i in range(3):
task = asyncio.create_task(worker(f'worker-{i}', queue))
tasks.append(task)
# Wait until the queue is fully processed.
started_at = time.monotonic()
await queue.join()
total_slept_for = time.monotonic() - started_at
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
print('====')
print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
print(f'total expected sleep time: {total_sleep_time:.2f} seconds')
asyncio.run(main())
底层 API:Future 与事件循环
Future 对象
文档位于 asyncio-future.rst。Future 对象用于把低层基于回调的代码与高层 async/await 代码桥接起来,表示异步操作的最终结果,非线程安全。规则是:永远不要向用户暴露 Future;推荐的创建方式是 loop.create_future(),这样第三方事件循环可注入优化实现。Python 3.7 起支持 contextvars。
常用函数:
asyncio.isfuture(obj):判断对象是否为asyncio.Future实例、asyncio.Task实例或带_asyncio_future_blocking属性的 Future 风格对象(Python 3.5 起)。asyncio.ensure_future(obj, *, loop=None):若obj是 Future/Task/Future 风格对象则原样返回;若是协程则包装为 Task;若是其他可等待对象则包装成会 await 它的 Task;都不是则抛TypeError。创建新 Task 的首选仍是create_task。asyncio.wrap_future(future, *, loop=None):把concurrent.futures.Future包装为asyncio.Future。
Future 核心方法:result()(返回结果;被取消抛 CancelledError;未就绪抛 InvalidStateError)、set_result(result)(标记完成并设置结果,已 done 时抛 InvalidStateError)、set_exception(exception)(标记完成并设置异常)、done()、cancelled()、cancel()(已 done/cancelled 返回 False,否则置为 cancelled、调度回调并返回 True)、exception()、add_done_callback(callback, *, context=None)(Future 已 done 时通过 loop.call_soon 调度;可用 functools.partial 传参;context 参数 Python 3.7 新增)、remove_done_callback(callback)、get_loop()(Python 3.7 新增)。
Future 与 concurrent.futures.Future 的关键差异:后者不可 await;asyncio 的 result()/exception() 不接受 timeout;未完成时抛 InvalidStateError 而非阻塞;回调不是立即执行而是经 loop.call_soon 调度;asyncio Future 不兼容 concurrent.futures.wait 与 as_completed。
示例:创建 Future,用 Task 异步设置其结果:
async def set_after(fut, delay, value):
# Sleep for *delay* seconds.
await asyncio.sleep(delay)
# Set *value* as a result of *fut* Future.
fut.set_result(value)
async def main():
# Get the current event loop.
loop = asyncio.get_running_loop()
# Create a new Future object.
fut = loop.create_future()
# Run "set_after()" coroutine in a parallel Task.
loop.create_task(set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it.
print(await fut)
asyncio.run(main())
事件循环(Event Loop)
文档位于 asyncio-eventloop.rst。事件循环是每个 asyncio 应用的核心:运行异步任务和回调、执行网络 IO、运行子进程。应用开发者通常应使用高层函数(如 asyncio.run),很少需要引用循环对象;本节主要面向库和框架开发者。
获取事件循环:
asyncio.get_running_loop():返回当前 OS 线程中运行的事件循环;没有运行中的循环则抛RuntimeError,只能在协程或回调中调用(Python 3.7 新增)。asyncio.get_event_loop():获取当前事件循环;若无则自动创建并设为当前。行为较复杂(尤其使用自定义事件循环策略时),协程/回调中优先用get_running_loop。asyncio.set_event_loop(loop):把loop设为当前线程的事件循环。asyncio.new_event_loop():创建新的事件循环对象。
运行与停止循环:
loop.run_until_complete(future):运行直到 Future 完成;参数若是协程对象会隐式调度为 Task,返回 Future 结果或抛出异常。loop.run_forever():运行直到stop()被调用。若在run_forever()前调用stop(),循环以零超时轮询一次 IO selector,运行回调后退出;若运行中调用stop(),循环运行完当前批回调后退出(回调中新调度的回调要等下次运行)。loop.stop()/loop.is_running()/loop.is_closed()/loop.close()(关闭循环,须不在运行状态,清空所有队列并关闭执行器,幂等且不可逆)。loop.shutdown_asyncgens():关闭所有打开的异步生成器,之后新迭代会告警;用asyncio.run时无需手动调用。
调度回调:
loop.call_soon(callback, *args, context=None):在下一轮事件循环调用回调,按注册顺序,每个回调恰好调用一次,返回Handle可用于取消;非线程安全。loop.call_soon_threadsafe(callback, *args, context=None):线程安全版,必须用于从其他线程调度回调(Python 3.7 新增context参数)。- 大多数 asyncio 调度函数不支持关键字参数,需要时用
functools.partial。
调度延迟回调(事件循环用单调时钟计时):
loop.call_later(delay, callback, *args, context=None):延迟delay秒后调用一次,返回TimerHandle可取消;同一时刻的两个回调顺序未定义。loop.call_at(when, callback, *args, context=None):在绝对时间点when(与loop.time()同基准)调用。loop.time():返回事件循环内部单调时钟的当前时间(float)。- 注意:相对延迟或绝对时间不应超过一天(Python 3.7.0 及更早版本默认实现有此限制,3.7.1 修复)。
创建 Future 与 Task:
loop.create_future():创建绑定到循环的asyncio.Future(Python 3.5.2 起,是创建 Future 的首选)。loop.create_task(coro):调度协程执行并返回 Task 对象;第三方事件循环可用自己的 Task 子类。loop.set_task_factory(factory)/loop.get_task_factory():设置/获取任务工厂,工厂签名须为(loop, coro)并返回 Future 兼容对象。
网络连接与服务器(低层协议式 API):
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):打开流式 transport 连接。protocol_factory返回协议实现;成功后返回(transport, protocol)。底层时序:建立连接并创建 transport → 无参调用protocol_factory得到 protocol 实例 → 调用protocol.connection_made()把协议与 transport 耦合 → 返回元组。ssl传SSLContext或True(用ssl.create_default_context())开启 TLS;server_hostname用于证书匹配;ssl_handshake_timeout默认60.0秒(Python 3.7 新增)。自 Python 3.6 起所有 TCP 连接默认设置TCP_NODELAY。loop.create_datagram_endpoint(...):创建数据报(UDP)端点,socket 类型SOCK_DGRAM,支持local_addr、remote_addr、reuse_address(Unix 上默认True)、reuse_port、allow_broadcast、sock等参数。loop.create_unix_connection(...):Unix 域套接字连接(仅 Unix),path支持抽象 Unix 套接字、str、bytes、pathlib.Path(3.7 起 path-like)。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, start_serving=True):创建 TCP 服务器并返回Server对象。host可为字符串(绑定单个网卡)、字符串序列(绑定多个网卡)、空字符串或None(绑定所有网卡,返回多个 socket,通常 IPv4+IPv6 各一个);backlog默认 100;start_serving=True立即开始接受连接,为False时需 awaitServer.start_serving()或Server.serve_forever()。loop.create_unix_server(...):Unix 域套接字服务器(仅 Unix)。loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None):把已接受的连接包装成 transport/protocol 对,供在 asyncio 之外 accept、在 asyncio 内处理的服务器使用。
文件传输与 TLS:
loop.sendfile(transport, file, offset=0, count=None, *, fallback=True):通过 transport 发送文件,优先用高性能os.sendfile;平台不支持且fallback=False时抛SendfileNotAvailableError(Python 3.7 新增)。loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None):把现有 transport 连接升级为 TLS,返回新 transport 实例,原 transport 不得再使用(Python 3.7 新增)。
事件循环实现
SelectorEventLoop:基于selectors模块的事件循环,是 Unix 上的默认实现,仓库源码见 selector_events.py。ProactorEventLoop:Windows 上基于 I/O 完成端口的默认实现,仓库源码见 proactor_events.py。- 其余实现细节分散在 base_events.py、unix_events.py、windows_events.py。
异常(Exceptions)
文档位于 asyncio-exceptions.rst:
asyncio.TimeoutError:操作超过给定截止时间。注意:与内建TimeoutError不同。asyncio.CancelledError:操作被取消。可被捕获以执行自定义操作,但几乎所有情况下必须重新抛出。它是Exception的子类,可能被过宽的try..except Exception意外抑制:
try:
await operation
except Exception:
# The cancellation is broken because the *except* block
# suppresses the CancelledError exception.
log.log('an error has occurred')
应改为显式先捕获 CancelledError 并 re-raise:
try:
await operation
except asyncio.CancelledError:
raise
except Exception:
log.log('an error has occurred')
asyncio.InvalidStateError:Task 或 Future 内部状态非法(如给已有结果的 Future 再设置结果)。asyncio.SendfileNotAvailableError:对给定 socket/文件类型不可用sendfile系统调用,是RuntimeError子类。asyncio.IncompleteReadError(EOFError子类):请求的读操作未完整完成,由流 API 抛出;expected为期望字节数,partial为 EOF 前已读到的字节。asyncio.LimitOverrunError:查找分隔符时超过缓冲区大小上限,由流 API 抛出;consumed为已消耗的字节数。
源码佐证:asyncio 在仓库内的真实实现
文档描述与仓库实现一一对应,可交叉验证:
- Lib/asyncio/runners.py 中的
run():先检查events._get_running_loop()非空则抛RuntimeError("asyncio.run() cannot be called from a running event loop"),再校验参数是协程,随后new_event_loop()→set_event_loop(loop)→loop.set_debug(debug)→loop.run_until_complete(main),finally中取消所有任务、执行shutdown_asyncgens()、set_event_loop(None)并loop.close()——这与文档所述“始终创建新事件循环并在结束时关闭、负责收尾异步生成器”完全一致。 - Lib/asyncio/tasks.py 定义了
Task(继承futures._PyFuture)、create_task、gather、shield、wait_for、wait、as_completed、sleep、run_coroutine_threadsafe、current_task、all_tasks等全部高层原语。从源码可见Task.__init__会校验参数为协程(否则TypeError)、contextvars.copy_context()复制上下文,并通过self._loop.call_soon(self.__step, ...)立即调度——印证“create_task 之后协程自动尽快运行”。 - Lib/asyncio/init.py 导出了模块级公共 API,与文档各章节列出的函数一一对应。
在 KBEngine 服务器侧脚本中的实践建议
KBEngine 的服务器 Python 脚本运行于内嵌的 CPython 3.7.3,可直接使用上述 asyncio API。结合本文介绍的要点,实践中可注意:
- 程序入口统一用
asyncio.run(main()),避免手动管理事件循环的生命周期,且不要在一个运行中的循环里再次调用asyncio.run。 - 并发 IO 用
create_task+gather:例如批量请求多个外部服务、并行执行多条运维命令,gather保持结果顺序一致。 - 任何等待都要有超时意识:
wait_for用于给任务加超时;配合shield可在超时取消时不中断关键清理流程;CancelledError必须 re-raise,避免宽泛except Exception破坏取消语义。 - 网络协议开发优先使用 Streams:
open_connection/start_server让 TCP 客户端/服务器、HTTP 头探测等代码免于回调地狱;文件描述符已就绪的 socket 可用open_connection(sock=...)接入。 - 任务分发用
Queue+ 多个 worker Task:join()/task_done()组合可精确等待队列全部消费完毕;带超时的队列操作需用wait_for包装。 - 跨线程提交协程用
run_coroutine_threadsafe,且务必显式传入目标事件循环;子进程输出量大时用communicate()避免管道死锁。
参考文档索引
asyncio 全部章节文档均随仓库提供,可按需查阅:
- 总览:asyncio.rst
- 高层 API:协程与任务 asyncio-task.rst、流 asyncio-stream.rst、同步原语 asyncio-sync.rst、子进程 asyncio-subprocess.rst、队列 asyncio-queue.rst、异常 asyncio-exceptions.rst
- 底层 API:事件循环 asyncio-eventloop.rst、Future asyncio-future.rst、协议与传输 asyncio-protocol.rst、事件循环策略 asyncio-policy.rst、平台支持 asyncio-platforms.rst
- 指南:API 索引 asyncio-api-index.rst、开发指南 asyncio-dev.rst
- 实现源码:Lib/asyncio;测试用例:Lib/test/test_asyncio