gpt4 book ai didi

python - 在 asyncio.ensure_future 中捕获错误

转载 作者:太空狗 更新时间:2023-10-29 20:55:45 25 4
gpt4 key购买 nike

我有这个代码:

try:
asyncio.ensure_future(data_streamer.sendByLatest())
except ValueError as e:
logging.debug(repr(e))

data_streamer.sendByLatest() 可以引发 ValueError,但不会被捕获。

最佳答案

ensure_future - 只需创建 Task 并立即返回。您应该等待创建的任务以获取其结果(包括引发异常的情况):

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',)

如果您不打算在创建任务后立即等待它,您可以稍后等待它(以了解它是如何完成的):

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',)

关于python - 在 asyncio.ensure_future 中捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37001733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com