KBEngine 内置 Python 3.7 asyncio 高层 API 全索引:Tasks、Queues、Streams 与同步原语实战指南
KBEngine 内置 Python 3.7 asyncio 高层 API 全索引:Tasks、Queues、Streams 与同步原语实战指南
导读
本文以 KBEngine 仓库内置 Python 3.7.3 标准库文档中的 asyncio 高层 API 索引 为主体,系统梳理 asyncio 面向 async/await 的全部高层接口——从任务调度(Tasks)、队列分发(Queues)、子进程管理(Subprocesses)、网络流(Streams),到同步原语(Synchronization)与异常体系(Exceptions)。KBEngine 的服务器端 Python 脚本(如 kbe/res/sdk_templates/server/python_assets 中的服务端资产脚本)可直接使用这些接口编写异步逻辑;阅读本文后,你将掌握每一类 API 的用途、签名、默认值与典型代码范例,并能对照仓库内的 CPython 源码与单元测试深入理解其实现机制。
文档定位:KBEngine 内置的 Python 3.7 标准库文档
KBEngine 将完整的 CPython 源码树内置在仓库中,作为服务端脚本运行时的解释器来源,其位置与版本信息如下:
- 内置 Python 源码根目录:kbe/src/lib/python,其中 patchlevel.h 明确标注
PY_MAJOR_VERSION 3、PY_MINOR_VERSION 7、PY_MICRO_VERSION 3,即 Python 3.7.3; - asyncio 标准库实现:kbe/src/lib/python/Lib/asyncio,包含
tasks.py、queues.py、locks.py、streams.py、subprocess.py、runners.py、base_events.py等完整模块; - 本文主体文档:kbe/src/lib/python/Doc/library/asyncio-api-index.rst,是官方文档体系中“高层 API 索引”页面,按六大类(Tasks、Queues、Subprocesses、Streams、Synchronization、Exceptions)列出所有
async/await高层接口,并给出对应的示例链接; - 单元测试:kbe/src/lib/python/Lib/test/test_asyncio 下提供了
test_tasks.py、test_queues.py、test_locks.py、test_streams.py、test_subprocess.py、test_runners.py等测试文件,可直接验证下文所述行为。
从 asyncio/init.py 的导入链可以看到,高层 API 由 base_events、coroutines、events、futures、locks、protocols、runners、queues、streams、subprocess、tasks、transports 等子模块聚合导出;在 Windows 平台还会额外导出 windows_events。这意味着下文涉及的每个函数、类均可通过 asyncio.xxx 直接访问。
Tasks:程序的入口、任务调度与超时控制
Tasks 类 API 是所有 asyncio 程序的地基。索引文档将其定位为“运行 asyncio 程序、创建 Task、以及带超时地等待多个事物的工具集”,完整清单如下:
| API | 功能 |
|---|---|
run |
创建事件循环、运行协程、关闭事件循环(程序入口) |
create_task |
启动一个 asyncio Task |
await sleep |
休眠若干秒 |
await gather |
并发调度并等待多个事物 |
await wait_for |
带超时运行 |
await shield |
屏蔽取消(保护不被取消) |
await wait |
监控完成状态 |
current_task |
返回当前 Task |
all_tasks |
返回某个事件循环的全部 Task |
Task |
Task 对象 |
run_coroutine_threadsafe |
从其他 OS 线程调度协程 |
for in as_completed |
用 for 循环监控完成状态 |
程序入口 asyncio.run()
asyncio.run(main(), *, debug=False) 是官方推荐的唯一入口。从 runners.py 的源码可以看到其完整行为:先检查当前线程是否已有运行中的事件循环(若有则抛出 RuntimeError),随后新建事件循环、set_event_loop 并(可选)开启 debug 模式,通过 loop.run_until_complete(main) 执行协程;结束时 finally 块会先 _cancel_all_tasks 取消全部剩余任务,再执行 loop.shutdown_asyncgens() 终结异步生成器,最后 set_event_loop(None) 并 loop.close()。因此:
run()每次都会创建并关闭一个全新的事件循环,应当作为程序唯一入口只调用一次;- 不能在另一个运行中的事件循环内部调用它;
- 参数必须是协程(coroutine),否则抛出
ValueError。
任务的创建、查询与跨线程调度
create_task(coro)(tasks.py#L319)将协程包装为 Task 并调度到事件循环,是 3.7 起推荐替代ensure_future的方式;current_task(loop=None)与all_tasks(loop=None)(tasks.py#L27、tasks.py#L34)分别返回当前任务与事件循环上的全部任务;run_coroutine_threadsafe(coro, loop)(tasks.py#L796)用于“线程安全的调度”:它向目标循环提交一个回调,并返回一个concurrent.futures.Future,供调用方线程用.result()阻塞等待结果——这是多线程环境下从工作线程向事件循环线程投递协程的标准做法。
并发等待:gather、wait、as_completed
gather(*coros_or_futures, return_exceptions=False)(tasks.py#L634)并发调度所有传入的 awaitable 并聚合结果;若gather本身被取消,会级联取消尚未完成的子任务;若某个子任务被取消,则视为抛出CancelledError,但不会因此取消整个gather;wait(aws, *, timeout=None, return_when=ALL_COMPLETED)(tasks.py#L335)返回(done, pending)两个 Task/Future 集合,return_when支持FIRST_COMPLETED、FIRST_EXCEPTION、ALL_COMPLETED;as_completed(fs, *, timeout=None)(tasks.py#L488)返回一个迭代器,可在for循环中按“完成先后”逐个await,适合处理“先完成先处理”的场景。
索引文档引用的 gather 经典示例(factorial 并发计算)位于 asyncio-task.rst:
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())
# Expected output:
#
# Task A: Compute factorial(2)...
# Task B: Compute factorial(2)...
# Task C: Compute factorial(2)...
# Task A: factorial(2) = 2
# Task B: Compute factorial(3)...
# Task C: Compute factorial(3)...
# Task B: factorial(3) = 6
# Task C: Compute factorial(4)...
# Task C: factorial(4) = 24
注意三个任务“交错推进”而非串行执行——这正是 sleep 让出控制权、事件循环切换任务的结果。
超时、取消与屏蔽取消
wait_for(aw, timeout, *, loop=None)(tasks.py#L371):timeout为None时无限等待;超时后先取消任务再抛出asyncio.TimeoutError,且会等待任务真正完成取消,因此总等待时间可能略超timeout。文档强调:若要避免任务被取消,应把内部 awaitable 用shield包起来;shield(aw, *, loop=None)(tasks.py#L743):res = await shield(something())与res = await something()语义等价,区别在于外层协程被取消时something()不会收到取消,但外层await表达式仍会抛出CancelledError;若something()自身被取消,shield同样会取消。文档给出的彻底忽略取消(不推荐)写法是try: res = await shield(something()) except CancelledError: res = None;Task.cancel()与CancelledError:cancel()会在事件循环下一轮迭代时向协程内抛入CancelledError(asyncio-task.rst#L664),协程可以在except CancelledError中清理资源,甚至(虽不推荐)抑制取消。
wait_for 超时示例(asyncio-task.rst#L437):
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!
任务取消拦截示例(asyncio-task.rst#L699):
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())
sleep(delay, result=None, *, loop=None)(tasks.py#L555)始终挂起当前任务让其他任务执行;索引文档引用的“每秒打印一次当前时间共 5 秒”示例见 asyncio-task.rst#L279,其中通过 loop.time() 计算绝对截止时间。
Queues:多任务之间的工作分发
索引文档明确指出 Queues 的三大典型用途:在多个 asyncio Task 之间分发工作、实现连接池、实现发布/订阅(pub/sub)模式。其完整清单如下:
| API | 功能 |
|---|---|
Queue |
FIFO(先进先出)队列 |
PriorityQueue |
优先级队列 |
LifoQueue |
LIFO(后进先出)队列 |
实现位于 queues.py:
Queue(maxsize=0)(queues.py#L20):maxsize=0表示无上限;核心方法put()/get()是可等待协程(队列满时put挂起、空时get挂起),另有put_nowait()/get_nowait()非阻塞版本,以及qsize()、empty()、full()、task_done()、join();PriorityQueue(Queue)(queues.py#L219):内部用heapq.heappush/heappop实现小顶堆,元素按优先级出队;LifoQueue(Queue)(queues.py#L235):出队顺序与入队顺序相反(栈语义)。
典型的“生产者—消费者”协作模式是:多个 worker Task 循环执行 item = await queue.get(),处理完调用 queue.task_done(),主协程 await queue.join() 等待所有任务处理完毕。索引文档对应的分发示例位于 asyncio-queue.rst(其 asyncio_example_queue_dist 锚点),实现细节同样可对照 test_queues.py 中的行为断言。
Subprocesses:异步子进程与 Shell 命令
Subprocesses 类 API 用于“派生子进程并运行 Shell 命令”,完整清单如下:
| API | 功能 |
|---|---|
await create_subprocess_exec |
创建子进程 |
await create_subprocess_shell |
运行一条 Shell 命令 |
实现位于 subprocess.py:
create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, ...)(subprocess.py#L206):直接以程序路径 + 参数列表启动,不经 Shell 解析,适合参数含特殊字符或需要避免注入的场景;create_subprocess_shell(cmd, ...)(subprocess.py#L192):经系统 Shell 执行命令字符串;- 两者返回 Process 对象,提供
returncode、wait()、send_signal()、terminate()、kill()以及communicate(input=None)(同时读写 stdin/stdout/stderr 并等待结束)。
索引文档引用的 Shell 命令示例(asyncio-subprocess.rst#L12):
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
该文档还强调:由于子进程函数全部是异步的,可以非常自然地与 gather 组合并行执行多个命令:
async def main():
await asyncio.gather(
run('ls /zzz'),
run('sleep 1; echo "hello"'))
Streams:高层网络 IO
Streams 是“无需回调、无需底层 protocol/transport 即可收发网络数据”的高层 API,完整清单如下:
| API | 功能 |
|---|---|
await open_connection |
建立 TCP 连接 |
await open_unix_connection |
建立 Unix 套接字连接 |
await start_server |
启动 TCP 服务器 |
await start_unix_server |
启动 Unix 套接字服务器 |
StreamReader |
接收网络数据的高层 async/await 对象 |
StreamWriter |
发送网络数据的高层 async/await 对象 |
实现位于 streams.py:
open_connection(host=None, port=None, *, limit=None, ssl=None, ...)(streams.py#L53)返回(reader, writer)二元组;limit决定StreamReader缓冲区上限,默认 64 KiB;其余参数直接透传给loop.create_connection;start_server(client_connected_cb, host=None, port=None, *, backlog=100, ...)(streams.py#L82):每个新连接到达时调用client_connected_cb(reader, writer),回调可以是普通可调用对象或协程函数(协程函数会被自动调度为 Task);start_serving=True(默认)表示立即开始接受连接;open_unix_connection/start_unix_server(streams.py#L120、streams.py#L132)为 Unix 域套接字版本,仅 Unix 平台可用;- StreamReader 提供
read(n)、readline()、readexactly(n)等可等待读方法;StreamWriter 提供write()、drain()(背压控制)、close()、wait_closed()、write_eof()等。
索引文档引用的 TCP 回显客户端示例(asyncio-stream.rst#L13):
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!'))
对称地,服务端可以用 start_server 实现回显逻辑;流式 API 的更多边界行为(如缓冲上限触发、EOF 处理、LimitOverrunError)可对照 test_streams.py 验证。
Synchronization:类线程的同步原语
同步原语“专供 Task 内部使用,与 threading 模块形态相似但有两个重要区别”(asyncio-sync.rst):
- 不是线程安全的——不要用它做 OS 线程同步(那应该用
threading); - 方法不接受
timeout参数——需要超时请用asyncio.wait_for包裹。
完整清单如下:
| API | 功能 |
|---|---|
Lock |
互斥锁 |
Event |
事件对象 |
Condition |
条件对象 |
Semaphore |
信号量 |
BoundedSemaphore |
有界信号量 |
实现位于 locks.py:
- Lock(互斥锁):推荐
async with lock:写法,等价于await lock.acquire()+try/finally: lock.release(); - Event:内部布尔标志,
set()置真并唤醒所有等待者、clear()复位、is_set()查询、wait()阻塞至标志为真(已置真则立即返回); - Condition:提供
wait()、wait_for(predicate)、notify(n=1)、notify_all(); - Semaphore 与
BoundedSemaphore:控制同时访问的许可数量,BoundedSemaphore在release()超过初始值时会抛出ValueError。
索引文档引用的 Event 示例(asyncio-sync.rst#L97):
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())
各原语的获取/释放语义、唤醒顺序等细节可对照 test_locks.py 中的用例。
Exceptions:asyncio 专属异常
索引文档专门列出两个高频异常,并特别给出两个易错点(asyncio-exceptions.rst):
| 异常 | 说明 |
|---|---|
asyncio.TimeoutError |
由 wait_for 等函数在超时时抛出。注意它与内建 TimeoutError 无关 |
asyncio.CancelledError |
当 Task 被取消时抛出(参见 Task.cancel()) |
CancelledError是Exception的子类,因此一个过宽的except Exception:会意外吞掉取消请求,导致“取消失效”。文档给出的正确模式是:
try:
await operation
except asyncio.CancelledError:
raise
except Exception:
log.log('an error has occurred')
- 索引文档提及的取消清理示例同样位于 asyncio-task.rst#L699。
除此之外,asyncio-exceptions.rst 还定义了 InvalidStateError(Task/Future 内部状态非法,如对已有结果的 Future 再次 set_result)、SendfileNotAvailableError(系统不支持 sendfile,RuntimeError 子类)、IncompleteReadError(流式读取未读满,EOFError 子类,含 expected/partial 属性)与 LimitOverrunError(查找分隔符时超过缓冲上限,含 consumed 属性)。
从源码与测试验证这些行为
如果希望在本仓库内直接验证上述 API 的行为,可以查看并运行内置测试套件:
- 行为断言:任务调度与取消见 test_tasks.py,事件循环见 test_runners.py,队列见 test_queues.py,同步原语见 test_locks.py,流见 test_streams.py,子进程见 test_subprocess.py;
- 实现源码:所有高层 API 的定义集中在 kbe/src/lib/python/Lib/asyncio 目录,读者可以顺着上述行号逐一查看
gather、wait_for、shield、Queue、Lock、open_connection、create_subprocess_shell等的真实实现; - 内置 Python 版本:3.7.3,对应标准库为
asyncio3.7 时代 API——例如asyncio.run()(3.7 新增)、create_task()(3.7 起推荐)、asyncio.TimeoutError与内建TimeoutError分离等版本特性均以本仓库内置解释器为准。
总结:一张表快速定位高层 API
| 类别 | 入口函数/类 | 典型场景 |
|---|---|---|
| Tasks | run、create_task、sleep、gather、wait_for、shield、wait、as_completed、current_task、all_tasks、Task、run_coroutine_threadsafe |
程序入口、并发调度、超时/取消控制、跨线程投递 |
| Queues | Queue、PriorityQueue、LifoQueue |
任务分发、连接池、pub/sub |
| Subprocesses | create_subprocess_exec、create_subprocess_shell |
异步执行外部命令与子进程 |
| Streams | open_connection、open_unix_connection、start_server、start_unix_server、StreamReader、StreamWriter |
高层 TCP/Unix 网络编程 |
| Synchronization | Lock、Event、Condition、Semaphore、BoundedSemaphore |
Task 间互斥、通知、流量控制 |
| Exceptions | asyncio.TimeoutError、asyncio.CancelledError |
超时与取消的异常处理 |
在 KBEngine 内置 Python 3.7.3 环境下,服务端脚本可以直接 import asyncio 并组合上述 API:以 run() 为入口、create_task/gather 组织并发、Queue 实现消息分发、Streams 承载自定义网络协议、Lock/Event 协调多任务,配合 wait_for 与 CancelledError 的规范处理,即可构建健壮的异步逻辑。