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

Can't get the stack trace using asyncio.ensure_future()

这是我试过的:

>>> 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()) 没有问题。

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