作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
说明:(简体)
import asyncio
async def download(data):
filename = "*" if data in ["b", "c"] else data # simulated failure
with open(filename, "w") as f:
f.write(data)
async def coro(data_list):
coroutines = [download(data) for data in data_list]
for coroutine in asyncio.as_completed(coroutines):
await coroutine
async def main():
task1 = asyncio.create_task(coro(["a", "b", "c"]))
task2 = asyncio.create_task(coro(["d", "e", "f"]))
results = await asyncio.gather(task1, task2, return_exceptions=True)
for _ in results:
pass
asyncio.run(main())
输出:(简化)
Task exception was never retrieved
future: <Task finished coro=<download() done, defined at D:/myscript.py:2> exception=OSError(22, 'Invalid argument')>
Traceback (most recent call last):
File "D:/myscript.py", line 4, in download
with open(filename, "w") as f:
OSError: [Errno 22] Invalid argument: '*'
最佳答案
如果你想收集异常而不是引发它们,你可以使用 asyncio.gather(return_exceptions=True)
在 coro
以及。例如:
import asyncio
async def download(data):
if data in ['b', 'c']:
1/0 # simulate error
return 42 # success
async def coro(data_list):
coroutines = [download(data) for data in data_list]
return await asyncio.gather(*coroutines, return_exceptions=True)
async def main():
task1 = asyncio.create_task(coro(["a", "b", "c"]))
task2 = asyncio.create_task(coro(["d", "e", "f"]))
return await asyncio.gather(task1, task2, return_exceptions=True)
print(asyncio.run(main()))
这将打印:
[[42, ZeroDivisionError('division by zero'), ZeroDivisionError('division by zero')], [42, 42, 42]]
关于Python - asyncio - 从未检索到任务异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65147823/
背景 我最近在 merge 期间遇到了一个意外未 merge 的文档文件的问题。 无论出于何种原因,我搞砸了 merge 并有效地删除了文件(和其他几个文件),因为我忘记了它们的存在。 现在我想查看我
我在我的网站上使用旧的 mysql 版本和 php 版本 4。 我的表结构: | orders_status_history_id | orders_id | orders_status_id |
我是一名优秀的程序员,十分优秀!