利用 asyncio.wait 精确控制子任务超时行为,核心在于调用时传入 timeout 参数,并处理其返回的已完成与未完成任务集合。通过检查 done 集合中的任务状态,可以区分正常完成和因超时而取消的任务,从而执行相应的清理或重试逻辑。

如何获取已完成的子任务结果?
当 asyncio.wait 返回后,done 集合包含所有已结束的任务(包括正常完成和被取消的)。要获取结果,需遍历 done 集合,对每个任务调用 result() 方法。若任务因超时而取消,调用 result() 会抛出 CancelledError,因此需要先检查任务是否被取消。

import asyncio
async def task(name, duration):
print(f"Task {name} started")
await asyncio.sleep(duration)
print(f"Task {name} finished")
return f"Result from {name}"
async def main():
tasks = [
asyncio.create_task(task("A", 1)),
asyncio.create_task(task("B", 2)),
asyncio.create_task(task("C", 0.5))
]
# 设置总超时时间为 1.5 秒
done, pending = await asyncio.wait(tasks, timeout=1.5)
results = []
for t in done:
if t.cancelled():
print(f"Task {t.get_name()} was cancelled")
else:
try:
res = t.result()
results.append(res)
print(f"Got result: {res}")
except Exception as e:
print(f"Task failed with exception: {e}")
# 取消剩余未完成的任务
for t in pending:
t.cancel()
try:
await t
except asyncio.CancelledError:
pass
print(f"Final results: {results}")
asyncio.run(main())
如何处理超时后的资源清理?
超时后,pending 集合中包含尚未完成的任务。这些任务可能持有锁、网络连接或其他资源。必须显式调用 t.cancel() 来请求取消它们,并等待它们结束以释放资源。忽略这一步可能导致资源泄漏或程序挂起。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
async def long_running_task():
print("Long task starting")
try:
# 模拟长时间操作,如网络请求
await asyncio.sleep(10)
return "Success"
except asyncio.CancelledError:
print("Long task cancelled, cleaning up resources")
raise
async def main():
task_obj = asyncio.create_task(long_running_task())
try:
done, pending = await asyncio.wait({task_obj}, timeout=2.0)
except asyncio.TimeoutError:
# 如果 wait 本身超时(虽然这里用 timeout 参数不会抛 TimeoutError)
pass
if task_obj in pending:
print("Task timed out, cancelling...")
task_obj.cancel()
try:
await task_obj
except asyncio.CancelledError:
print("Task successfully cancelled")
asyncio.run(main())
当子任务抛出异常时,wait 的行为是什么?
asyncio.wait 不会自动捕获子任务中抛出的异常。如果某个任务在运行期间抛出异常,该任务的状态会变成 finished,但其 result() 调用将重新抛出该异常。因此,在遍历 done 集合时,必须使用 try-except 块来捕获和处理这些异常,否则异常会传播到主协程并导致程序终止。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










