使用 asyncio.shield() 可以保护关键任务不被意外取消,具体做法是将需要保护的任务包装在 shield 中并作为协程 await。这样即使外层任务被取消,被保护的任务也会继续运行直到完成或自身被显式取消,从而避免资源泄露或状态不一致。

如何验证 shield 阻止了外部 CancelledError?
通过创建一个模拟长时间运行的任务,并在其执行过程中取消包含它的父协程,可以验证 asyncio.shield() 的行为。父协程会抛出 CancelledError,但被 shield 包裹的子任务会继续执行完毕。

import asyncio
async def critical_task():
print("Critical task started")
await asyncio.sleep(5)
print("Critical task finished")
return "success"
async def parent_task():
try:
result = await asyncio.shield(critical_task())
print(f"Shielded result: {result}")
except asyncio.CancelledError:
print("Parent task was cancelled, but shielded task continues")
raise
async def main():
task = asyncio.create_task(parent_task())
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Wait for the critical task to finish in background
await asyncio.sleep(5)
asyncio.run(main())
预期结果:父任务在1秒后取消并抛出异常,但控制台会显示“Critical task started”和“Critical task finished”,证明子任务未被中断。
shield 返回值的类型和获取方式是什么?
asyncio.shield() 返回的是一个 Task 对象,该对象代表被保护的任务。可以通过 await 这个 Task 对象来获取最终结果。如果任务正常完成,await 将返回任务的返回值;如果任务因自身原因失败,将抛出相应的异常。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
async def data_fetcher():
await asyncio.sleep(2)
return {"data": "important_info"}
async def monitor():
shielded = asyncio.shield(data_fetcher())
try:
result = await shielded
print(f"Fetched data: {result}")
except asyncio.CancelledError:
print("Monitor cancelled, but fetcher continues")
raise
async def main():
task = asyncio.create_task(monitor())
await asyncio.sleep(0.5)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
await asyncio.sleep(2)
asyncio.run(main())
预期结果:monitor 任务被取消,但 data_fetcher 继续运行并最终打印出 fetched data。shielded 变量是一个 Task 实例,await 它即获得原始返回值。
如果被保护的任务自身抛出异常,shield 会如何处理?
如果被保护的任务自身抛出异常(非 CancelledError),asyncio.shield() 会将该异常传播给 await 它的调用者。shield 仅屏蔽外部的取消操作,不掩盖任务内部的错误。调用者必须通过 try-except 捕获这些异常以进行适当处理。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










