在 python 3.11 中,应使用 asyncio.timeout() 上下文管理器替代旧版的 asyncio.wait_for()。具体做法是将需要超时的异步代码块包裹在 async with asyncio.timeout(seconds): 语句中,当执行时间超过指定秒数时,会自动抛出 asyncio.timeouterror。这种方式比 wait_for() 更灵活,因为它允许在超时发生时保留当前的协程状态,且支持嵌套超时控制。

如何替换旧的 wait_for 调用?
将 await asyncio.wait_for(coro, timeout) 替换为 async with asyncio.timeout(timeout): await coro。这种替换保持了相同的超时行为,但提供了更清晰的代码结构和更好的错误处理机制。

import asyncio
async def fetch_data():
# 模拟耗时操作
await asyncio.sleep(5)
return "data"
async def main():
try:
async with asyncio.timeout(2):
result = await fetch_data()
print(f"Result: {result}")
except asyncio.TimeoutError:
print("Operation timed out")
asyncio.run(main())运行上述代码将输出:Operation timed out,因为 fetch_data 需要 5 秒,而超时设置为 2 秒。
立即学习“Python免费学习笔记(深入)”;
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
嵌套超时如何处理?
在 Python 3.11 中,asyncio.timeout() 支持嵌套使用。内层超时会覆盖外层超时,形成独立的超时作用域。例如,在外层设置 10 秒超时,内层设置 2 秒超时,内层操作超过 2 秒即触发超时,而不受外层 10 秒限制。

import asyncio
async def inner_task():
await asyncio.sleep(3)
return "inner done"
async def outer_task():
async with asyncio.timeout(10):
async with asyncio.timeout(2):
result = await inner_task()
print(f"Inner result: {result}")
async def main():
try:
await outer_task()
except asyncio.TimeoutError:
print("Timeout occurred")
asyncio.run(main())运行结果:Timeout occurred,因为内层任务超过 2 秒超时,尽管外层允许 10 秒。
超时异常的具体类型是什么?
当 asyncio.timeout() 触发超时时,抛出的异常是 asyncio.TimeoutError。该异常继承自 Exception,可以通过 except asyncio.TimeoutError: 捕获。与旧版 wait_for() 不同,新版不会自动取消协程,而是通过上下文管理器的退出逻辑处理超时,开发者可以手动决定是否需要取消正在运行的协程。

















