gpt4 book ai didi

python - 无法使用 asyncio.ensure_future() 获取堆栈跟踪

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:41 25 4
gpt4 key购买 nike

这是我尝试过的:

>>> import asyncio
>>> @asyncio.coroutine
... def f():
... print("RUN")
... raise Exception("ciao")
...
>>> asyncio.ensure_future(f())
<Task pending coro=<coro() running at /usr/lib/python3.4/asyncio/coroutines.py:139>>
>>> loop = asyncio.get_event_loop()
>>> loop.run_forever()
RUN

并且未检索到堆栈跟踪。如果我使用 asyncio.run_until_complete(f()) 运行协程,则没有问题。

最佳答案

您必须在某处等待协程的结果,并且会在该上下文中引发异常。所有协程都需要“等待”; asyncio.run_until_complete() 会隐式地为您执行此操作,但 run_forever() 不能,因为它应该永远运行。下面是一个如何查看异常的示例(使用 Python 3.5 语法):

>>> import asyncio
>>> import traceback
>>> async def f():
... raise Exception("Viva la revolución!")
...
>>> task_f = asyncio.ensure_future(f())
>>> async def g():
... try:
... await task_f
... except Exception:
... traceback.print_exc()
...
>>> task_g = asyncio.ensure_future(g())
>>> asyncio.get_event_loop().run_forever()
Traceback (most recent call last):
File "<ipython-input-5-0d9e3c563e35>", line 3, in g
await task_f
File "/usr/lib/python3.5/asyncio/futures.py", line 363, in __iter__
return self.result() # May raise too.
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "<ipython-input-3-928dc548dc3e>", line 2, in f
raise Exception("Viva la revolución!")
Exception: Viva la revolución!

关于python - 无法使用 asyncio.ensure_future() 获取堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141669/

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