documentation for asyncio.gather人说
如果return_exceptions为
False
(默认),则引发的第一个异常为
然而,从一个简单的测试来看,如果其中一个任务在return_exceptions为False
时引发异常,那么所有其他等待的任务都将被取消(或者更准确地说,如果我不清楚术语,其他等待的任务将无法完成其工作):
import asyncio
async def factorial(name, number, raise_exception=False):
# If raise_exception is True, will raise an exception when
# the loop counter > 3
f = 1
for i in range(2, number + 1):
print(f' Task {name}: Compute factorial({i})...')
if raise_exception and i > 3:
print(f' Task {name}: raising Exception')
raise Exception(f'Bad Task {name}')
await asyncio.sleep(1)
f *= i
print(f'==>> Task {name} DONE: factorial({number}) = {f}')
return f
async def main():
tasks = [factorial('A', 5), # this will not be finished
factorial('B', 10, raise_exception=True),
factorial('C', 2)]
try:
results = await asyncio.gather(*tasks)
print('Results:', results)
except Exception as e:
print('Got an exception:', e)
asyncio.run(main())
这段代码所做的只是为了简化,它定义了3个任务,并调用了asyncio.gather()
个.其中一个任务在另一个任务完成之前引发异常,而另一个任务未完成.
事实上,我甚至无法理解文档中所说的内容——如果一个异常被等待gather
的任务引发并捕获,我甚至无法获得返回的结果(即使另一个任务以某种方式完成).
我遗漏了什么,或者文档有问题吗?
这是用Python 3.7.2测试的.