You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10+中asyncio.wait_for的TimeoutError未正确处理问题

Python 3.10+ 中 asyncio.wait_for 捕获超时异常的正确方式

你的代码问题出在异常捕获的类不匹配:asyncio.wait_for()抛出的是asyncio模块专属的TimeoutError,而你代码里直接写的except TimeoutError默认匹配的是Python内置的TimeoutError(属于builtins模块),两者不是同一个类,所以无法捕获到超时异常。

修正后的代码有两种写法:

写法1:明确指定捕获 asyncio 的 TimeoutError

import asyncio

async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    print('wait for at most 1 second...')
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError: 
        print('timeout!')

asyncio.run(main())

写法2:单独导入 asyncio 的 TimeoutError

import asyncio
from asyncio.exceptions import TimeoutError

async def eternity():
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    print('wait for at most 1 second...')
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except TimeoutError: 
        print('timeout!')

asyncio.run(main())

Python 3.10+ 中,asyncio.TimeoutError是asyncio.exceptions.TimeoutError的别名,两种写法都能正常捕获超时异常。运行修正后的代码,会在1秒后输出timeout!,符合预期。

内容的提问来源于stack exchange,提问作者darren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:15:18