python-3.x - 为什么会立即从 asyncio 任务中引发此异常?
问题描述
我从文档中的理解是,asyncio.Tasks 作为 asyncio.Future 的子类,将存储其中引发的异常,并且可以在我闲暇时检索它们。
但是,在此示例代码中,会立即引发异常:
import asyncio
async def bad_task():
raise Exception()
async def test():
loop = asyncio.get_event_loop()
task = loop.create_task(bad_task())
await task
# I would expect to get here
exp = task.exception()
# but we never do because the function exits on line 3
loop = asyncio.get_event_loop()
loop.run_until_complete(test())
loop.close()
示例输出(Python 3.6.5):
python3 ./test.py
Traceback (most recent call last):
File "./test.py", line 15, in <module>
loop.run_until_complete(test())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 468, in run_until_complete
return future.result()
File "./test.py", line 9, in test
await task
File "./test.py", line 4, in bad_task
raise Exception()
Exception
这是在异步代码中创建和调用任务的怪癖吗?
解决方案
await
将引发任务抛出的任何异常,因为它旨在使异步代码看起来几乎与同步代码完全相同。如果你想抓住它们,你可以使用普通try...except
子句。
推荐阅读
- java - 如何使用 Spring Data JPA 访问 Azure AD 集成 Postgres DB?
- django - 单个对象解析器的 DjangoListField 类比
- javascript - NodeJS - 2 个进程中的一个类/模块实例
- python - 我是 jupyter 的新手,不明白这个错误,我正在寻找删除 $ 符号
- python - 我将文件名添加到数据框中,但它只添加了相同的名称
- javascript - 在 JavaScript、React 中将命名范围解码为 Excel 文件中的表格
- python - Heroku 和 Praw (Reddit API) submit.reply()
- streaming - Streamlabs bot(?也许只是一个脚本):如何制作一个
- excel - 使用 Excel 创建 AD 用户
- python - 如何将嵌套列表的列作为新的单独嵌套列表获取