[英]Using nested asyncio.gather() inside another asyncio.gather()
[英]How to ensure all task are executed using asyncio.gather?
使用asyncio.gather
時,當其中一個任務引發異常時,所有任務都不會執行:
# coding: utf-8
import asyncio
async def foo(i):
await asyncio.sleep(0.1)
if i == 2:
print("2: 1/0")
1/0
print(i)
async def main():
futures = []
for i in range(1000):
futures.append(foo(i))
await asyncio.gather(*futures)
asyncio.run(main())
0
1
2: 1/0
3
4
5
6
7
[...]
501
502
503
504
Traceback (most recent call last):
File "<input>", line 24, in <module>
File "/usr/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "<input>", line 21, in main
File "<input>", line 9, in foo
ZeroDivisionError: division by zero
如何確保在退出asyncio.gather
之前執行所有任務? 我知道這不可能是asyncio.gather
的默認行為,因為如果我的一項任務從未完成,則永遠不會引發異常。 我的問題更多:如何執行一組任務收集並等待所有完成/提升后再繼續?
我認為您想密切關注asyncio.gather 的文檔:
如果 return_exceptions 為 False(默認值),則第一個引發的異常會立即傳播到在 gather() 上等待的任務。 aws 序列中的其他等待對象不會被取消,並將繼續運行。
如果 return_exceptions 為 True,則將異常視為成功結果,並在結果列表中聚合。
根據我的閱讀,看起來如果您要像這樣調用asyncio.gather
......
await asyncio.gather(*futures, return_exceptions=True)
...你應該得到你想要的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.