问题描述
我想运行带有一些等待的 asyncio.gather,它可以引发 SystemExit。
import asyncio
async def func(t):
await asyncio.sleep(t)
raise SystemExit('Err')
async def main():
tasks = [asyncio.ensure_future(func(t)) for t in range(0,3)]
print('Starting gather')
try:
await asyncio.gather(*tasks,return_exceptions=True)
except BaseException:
pass
print('Gather returned')
for t in tasks:
if not t.done():
t.cancel()
try:
await t
except BaseException:
pass
await asyncio.sleep(1)
asyncio.run(main())
该代码段的退出代码为 1,因为 asnycio.run 将在其内部 cancel_all_tasks 中再次引发 SystemExit,它本身调用 tasks.gather。我如何防止这种行为,因此该代码段的退出代码将为 0(不会从 asyncio.run 中捕获异常)。
有没有办法阻止 cancel_all_tasks 看到我已经取消的任务? 是否有另一种解决方案,然后将 SystemExit 包装在 func 中?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)