捕获asyncio.ensure_future中的错误 [英] Catch errors in asyncio.ensure_future
本文介绍了捕获asyncio.ensure_future中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
try:
asyncio.ensure_future(data_streamer.sendByLatest())
except ValueError as e:
logging.debug(repr(e))
data_streamer.sendByLatest()
可以引发 ValueError
,但未捕获。
data_streamer.sendByLatest()
can raise a ValueError
, but it is not caught.
推荐答案
ensure_future
-只需创建 Task
并立即返回。您应该等待创建的任务获得结果(包括引发异常的情况):
ensure_future
- just creates Task
and return immediately. You should await for created task to get it's result (including case when it raises exception):
import asyncio
async def test():
await asyncio.sleep(0)
raise ValueError('123')
async def main():
try:
task = asyncio.ensure_future(test()) # Task aren't finished here yet
await task # Here we await for task finished and here exception would be raised
except ValueError as e:
print(repr(e))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
ValueError('123',)
如果您不打算在创建任务后立即等待任务,则可以稍后等待(以了解任务的完成方式):
In case you aren't planning to await task immediately after you created it, you can await it later (to know how it has finished):
async def main():
task = asyncio.ensure_future(test())
await asyncio.sleep(1)
# At this moment task finished with exception,
# but we didn't retrieved it's exception.
# We can do it just awaiting task:
try:
await task
except ValueError as e:
print(repr(e))
输出相同:
ValueError('123',)
这篇关于捕获asyncio.ensure_future中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文