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

时间:2016-12-14 11:39:14

标签: python stack-trace python-asyncio

这就是我的尝试:

>>> 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())运行协程,则没有问题。

1 个答案:

答案 0 :(得分:3)

你必须在某处等待协同程序的结果,并且在该上下文中将引发异常。所有协同程序都需要“等待”; 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!