asyncio 取消与超时:六处不报错的失效点(实测)
TL;DR:asyncio 里的取消是一次异常,超时是取消的二次包装。这两件事有六个地方既不抛错也不写日志:except Exception 看不见 CancelledError;except OSError 会把超时和网络错误一起吞掉;wait_for 的 deadline 能被内层协程吃成一个「业务返回值」;asyncio.timeout() 打不断同步阻塞;shield 之后内层抛出的异常没人认领;run_in_executor 的 cancel() 只改了 Future 的状态。六个场景我都在 CPython 3.13.14 加 Windows 11 上真跑了一遍,下面每条都附可复制脚本与修法。
先说清楚为什么这六处都不会报错
asyncio 的取消机制只有两个动作:取消是在目标任务的某个 await 点上抛出 asyncio.CancelledError;超时是定时器到点后对当前任务发起取消,再由上下文管理器在退出时把 CancelledError 转换成 TimeoutError。
官方文档把第二句话写在 asyncio.timeout() 的 Note 里:「The asyncio.timeout() context manager is what transforms the asyncio.CancelledError into a TimeoutError, which means the TimeoutError can only be caught *outside* of the context manager.」
这两句话能推出三件事,六个坑全部由它们派生:
- 取消与超时走同一条通道,谁把
CancelledError接住吃掉,超时就一起消失,而且不报错。 CancelledError自 Python 3.8 起直接继承BaseException,except Exception这一层完全看不到它。- 取消只能落在
await点上,手里没有 await 的同步代码收不到任何信号。
环境与复现命令
python -V
# Python 3.13.14
文档口径读自 docs.python.org/3(2026-11-01 抓取)。我实际在本机跑了二十来段最小复现,下面每个数字都是脚本打印出来的:CPython 3.13.14 加 Windows 11。
坑一 except Exception 抓不到取消
import asyncio
async def child():
try:
await asyncio.sleep(5)
except Exception: # 以为能兜住一切
print("child caught something")
return "swallowed"
return "done"
async def main():
t = asyncio.create_task(child())
await asyncio.sleep(0.1)
t.cancel()
print(await t) # 这行不会被执行到
asyncio.run(main())
现象:await t 直接抛 CancelledError,child 里的 except Exception 一行日志都没打。如果这是后台任务(create_task 之后没人 await),异常就没人看见,进程正常退出。
口径:asyncio.CancelledError.__mro__ 是 CancelledError → BaseException → object,issubclass(CancelledError, Exception) 为 False。文档原话「Changed in version 3.8: CancelledError is now a subclass of BaseException rather than Exception.」
修法:清理逻辑放 finally;需要接住时用 except asyncio.CancelledError,收尾之后必须 raise。
坑二 except OSError 把超时一起吞了
import asyncio
async def slow():
await asyncio.sleep(10)
async def main():
try:
await asyncio.wait_for(slow(), timeout=0.05)
except OSError: # 本想兜网络类异常
print("网络异常分支被命中")
asyncio.run(main())
现象:打印「网络异常分支被命中」,日志里找不到 TimeoutError,上游以为是对端连接断了。
原因:Python 3.11 起 asyncio.TimeoutError 变成内置 TimeoutError 的别名(文档原话「Changed in version 3.11: This class was made an alias of TimeoutError.」),而内置 TimeoutError 在异常层级里挂在 OSError 下面(TimeoutError → OSError → Exception → BaseException)。于是 except OSError 顺手把超时也接住了。3.10 及以前两个类是互不相干的,同一段代码换旧版本不会出现这个现象。
修法:网络异常别用 OSError 一把兜;要精确就写 except TimeoutError,要兼容旧代码写 except (TimeoutError, asyncio.TimeoutError)(3.11 之后两者是同一个类)。
坑三 wait_for 的 deadline 被内层吃成假成功
import asyncio, time
async def stubborn():
try:
await asyncio.sleep(3)
except asyncio.CancelledError:
return "ignored cancel" # 收尾做完了,然后 return
async def main():
t0 = time.monotonic()
r = await asyncio.wait_for(stubborn(), timeout=0.05)
print(round(time.monotonic() - t0, 2), r)
asyncio.run(main())
实测输出是 0.06 ignored cancel,wait_for 没有抛 TimeoutError,调用方拿到一个来路正常的字符串。
原因分两层。一是 3.12 起 wait_for 改用 asyncio.timeout() 实现,官方改动记录写着「Changed in version 3.12: Implemented using asyncio.timeout(), a coroutine passed as *aw* is no longer wrapped in a Task when *timeout* is positive.」正超时下协程不再被包成独立任务,取消落在同一个任务的 await 点上,被内层的 try/except 直接接住。二是官方在 Task cancellation 小节自己写明了后果:「The asyncio components that enable structured concurrency, like asyncio.TaskGroup and asyncio.timeout(), are implemented using cancellation internally and might misbehave if a coroutine swallows asyncio.CancelledError.」
这不是孤例。CPython 关于 wait_for 吞取消的 issue 至今仍是 open 状态:gh-86296(原 bpo-42130),标题「AsyncIO's wait_for can hide cancellation in a rare race condition」;第三方项目 Tribler 的 issue #7570 把同一族问题(#86296 / #87555 / #81839)列为程序卡死的成因之一。
修法:接住取消必须 re-raise。确实想抑制取消,官方给的姿势是显式 uncancel():
except asyncio.CancelledError:
asyncio.current_task().uncancel()
return "suppressed"
实测两种写法的差别:raise 版在 0.06s 抛 TimeoutError;uncancel() 版在 0.06s 正常返回。前者是「超时生效」,后者是「我明确不要超时」,两者都能接受;只 try/except、既不 re-raise 也不 uncancel,才是那个 bug。
坑四 asyncio.timeout 打不断同步阻塞
import asyncio, time
async def main():
async with asyncio.timeout(0.05):
time.sleep(0.6)
asyncio.run(main())
实测:0.60s 后正常退出,没有 TimeoutError,实际耗时是 deadline 的 1200%。
原因很直白:取消只能在 await 点送达,而 time.sleep(0.6) 期间事件循环整个停摆,定时器回调根本没机会跑。
诊断命令,dev 模式会把卡住的回调打出来:
PYTHONDEVMODE=1 python your_script.py
# Executing > took 0.303 seconds
修法:阻塞调用换成 await asyncio.to_thread(func),或者把整段同步逻辑丢进 run_in_executor,再在外面套 timeout。
坑五 shield 之后内层异常没人认领
import asyncio
async def inner():
await asyncio.sleep(0.1)
raise RuntimeError("inner blew up after outer gave up")
async def main():
sh = asyncio.ensure_future(inner())
try:
await asyncio.wait_for(asyncio.shield(sh), timeout=0.02)
except TimeoutError:
print("外层已超时")
await asyncio.sleep(0.4)
asyncio.run(main())
现象:外层打印「外层已超时」,0.4s 之后 stderr 出现下面的内容。
Task exception was never retrieved
future: exception=RuntimeError('inner blew up after outer gave up')>
原因:shield 的语义就是「外层被取消,内层不受影响」,文档原话「*except* that if the coroutine containing it is cancelled, the Task running in something() is not cancelled」。超时返回之后这个 Task 还在跑,抛出的异常没有任何人 await 它,asyncio 只能在回收时打一条日志。同一页还有一条容易被忽略的 Important:「Save a reference to tasks passed to this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks.」连引用都不存,任务可能在跑完前就被 GC 回收。
修法:留引用,并注册回调把异常取走。
import asyncio
def _consume(t: asyncio.Task) -> None:
if not t.cancelled():
t.exception() # 取出来,避免 never retrieved
async def main():
sh = asyncio.ensure_future(inner())
sh.add_done_callback(_consume)
try:
await asyncio.wait_for(asyncio.shield(sh), timeout=0.02)
except TimeoutError:
sh.cancel() # 既然不要结果了,就明确取消
坑六 run_in_executor 的 cancel 只是改了个状态
import asyncio, threading, time
def blocking(counter, done):
for _ in range(20):
time.sleep(0.05)
counter[0] += 1
done.set()
async def main():
counter, done = [0], threading.Event()
loop = asyncio.get_running_loop()
fut = loop.run_in_executor(None, blocking, counter, done)
await asyncio.sleep(0.12)
fut.cancel()
print("cancelled()", fut.cancelled(), "n =", counter[0])
await asyncio.sleep(0.3)
print("0.3s 后 n =", counter[0], "线程结束吗", done.is_set())
asyncio.run(main())
实测输出:cancelled() True n = 2,然后 0.3s 后 n = 8 线程结束吗 False。线程最后跑到 n = 20 才结束。fut.cancelled() 为 True 只说明 asyncio 这一侧的 Future 被标记了,底层线程没有中断机制。
修法:线程池任务用协作式停止,拿一个 threading.Event 当停止信号,函数里每轮检查一次;需要硬中断就用 ProcessPoolExecutor,进程可以被 terminate。
两条补充观察也都不报错
- 第二次
cancel()会打断finally里的清理。实测第一次取消进入finally,里面await asyncio.sleep(0.3)做清理时再来一次取消,日志只剩['finally-enter', 'finally-cleanup-cancelled'],finally-cleanup-done永远不出现。清理要么在finally里用asyncio.shield保护,要么干脆不做长等待。 TaskGroup会吞掉子任务主动抛出的CancelledError,gather不会。同一个子协程里raise asyncio.CancelledError(...),TaskGroup上下文正常退出、无异常;gather直接把CancelledError抛给调用方。文档对前者的解释是「The first time any of the tasks belonging to the group fails with an exception other thanasyncio.CancelledError, the remaining tasks in the group are cancelled.」取消不算失败,所以不会被打包进ExceptionGroup。
一张对照表:取消送到之后实际发生了什么
| 写法 | 实测结果 |
|---|---|
wait_for(协程, 0.05) 且内层吞取消 | 0.06s 返回业务值,无异常 |
asyncio.timeout(0.05) 且内层吞取消 | 1.06s 正常退出,无异常 |
asyncio.timeout(0.05) 内放 time.sleep(0.6) | 0.60s 正常退出,无异常 |
wait_for(shield(task), 0.02) | 外层 TimeoutError,内层继续跑到抛异常 |
run_in_executor(...) 后 cancel() | cancelled() 为 True,线程跑满 20 轮 |
TaskGroup 子任务 raise CancelledError | 正常退出,无异常 |
gather 子任务 raise CancelledError | 抛出 CancelledError |
gather(return_exceptions=True) 含被取消任务 | 结果列表里是 CancelledError 对象 |
最后一行值得单独说:[type(x).__name__ for x in r] 实测得到 ['CancelledError', 'NoneType'],取消被伪装成「结果」。下游只判「这一项有没有值」,就会把一个被取消的任务当成返回了空。
正确的写法:五条规则
1. except asyncio.CancelledError 之后,清理完必须 raise;要抑制就调 uncancel()。
2. 不要用 except OSError 兜网络异常,用 TimeoutError 精确接。
3. 清理路径要短:finally 里的长 await 用 shield 包住,或者不做长等待。
4. 任何阻塞调用都换成 to_thread,否则超时只是写给自己看的。
5. shield 与 create_task 产生的任务必须留引用,并注册回调取走异常。
Troubleshooting:五条报错原文与修法
报错一:TypeError: Passing coroutines is forbidden, use tasks explicitly.
现象:await asyncio.wait([quick()]) 直接抛 TypeError,同时 stderr 出现 RuntimeWarning: coroutine 'quick' was never awaited。
原因:3.11 起 asyncio.wait() 不再接受裸协程,必须先包成任务。
修法:tasks = [asyncio.create_task(quick())] 之后再 await asyncio.wait(tasks)。
报错二:Task exception was never retrieved
现象:外层已经超时返回,几秒后 stderr 打出完整的 RuntimeError traceback。
原因:shield 让内层继续跑,而异常没人 await。
修法:见坑五,保存引用并 add_done_callback 取走 exception()。
报错三:TimeoutError 出现在「网络异常」分支里
现象:日志显示走了 except OSError,业务侧判定为对端断连。
原因:3.11 起 asyncio.TimeoutError is TimeoutError 为 True,而 TimeoutError 是 OSError 子类。
修法:把 except TimeoutError 与 except OSError 拆成两个分支,处理逻辑分开写。
报错四:ExceptionGroup 里只有一条 ValueError,兄弟任务的 finally 却执行了
现象:TaskGroup 抛出的 ExceptionGroup 只有 1 个元素,另一个任务的 finally 打了清理日志,看起来「被取消了却没人告诉它为什么」。
原因:兄弟任务收到的是 CancelledError,官方明确它不算失败,不会进 ExceptionGroup。
修法:需要知道谁被取消了就自己记账,别指望异常聚合。
报错五:退出时孤儿任务被静默取消
现象:create_task 出来的任务没存引用,主协程 return 后它的 finally 只执行一次,没有任何日志说明原因。
原因:asyncio.run() 在关闭事件循环前会取消所有 pending task。
修法:主协程退出前显式 cancel() 并 await,把收尾放在可观测的位置。
什么时候这些结论不成立
- 只在 Windows 11 加 CPython 3.13.14 上跑过。3.11 与 3.12 的行为差异只引官方
Changed in version记录,没有在本机做跨版本对拍。 - 没测 uvloop、anyio、trio。anyio 的 CancelScope 自己在调
uncancel(),两套取消语义混用是另一个话题(CPython gh-114496 讨论的就是这种混用)。 - 没测多线程加多事件循环,也没测信号处理路径里的取消。
wait_for吞取消还有一类原因是竞态:取消到达时任务恰好已经完成。本篇只覆盖「用户代码主动吞掉」这一类,竞态那类请看 gh-86296 原文。
FAQ
Q:except BaseException 是不是最保险?
不是。它会把 KeyboardInterrupt 和 SystemExit 一起收走,脚本的 Ctrl+C 会失灵。正确姿势是只接 asyncio.CancelledError,其余交给上层。
Q:3.11 之后还写 except asyncio.TimeoutError 有意义吗?
有,但要知道它和 TimeoutError 现在是同一个类,捕获范围完全一样;写旧名字只是保留可读性。
Q:cancel() 返回 True 就代表取消了?
不代表,它只表示取消请求已登记。实测对一个已完成的任务再 cancel() 返回 False;对 executor 的 future cancel() 之后 cancelled() 为 True,线程照样跑完。
Q:Task.cancelling() 什么时候有用?
排查「到底被取消了几次」的时候。实测第一次取消后 cancelling() 为 1,调用 uncancel() 归零,任务随后正常返回且 cancelled() 为 False。
Q:为什么我的清理代码从来没跑过?
两种常见原因:清理写在 except Exception 里,取消根本进不去;或者清理写在 finally 里并长时间 await,被第二次取消打断。
本文是纯技术复盘,不含任何联盟推广链接。相关阅读:进程层同样静默的超时问题见 subprocess 篇,网络层重试与超时叠加的实测见 requests 与 tenacity 篇,异步节点里 time.sleep 卡死事件循环的实测见 LangGraph 流式篇。
👉 立即参与小米 MiMo 开放平台:国内领先的 AI 大模型开放平台,高性价比推理服务
👉 立即参与阿里云 AI:汇集爆款 AI 产品,热门模型专属权益优惠券助力企业创新加速
📌 本文由 AI 辅助生成并经人工审核发布 | TechPassive — AI 驱动的内容测试站点,专注于效率工具与 SaaS 真实评测
🔗 精选推荐工具
使用以下链接支持我们持续产出高质量内容(点击可直接前往购买):
作为亚马逊联盟会员,符合条件的购买会为我们带来佣金,不会增加你的购买成本。