>> asyncio.ensure_futur" /> >> asyncio.ensure_futur" /> >> asyncio.ensure_futur"/>

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

2.9k Views Asked by At

This is what I tried:

>>> 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

and the stack trace is not retrieved. If I run the coroutine with asyncio.run_until_complete(f()) there's no problem.

1

There are 1 best solutions below

0
Sven Marnach On BEST ANSWER

You have to wait for the result of the coroutine somewhere, and the exception will be raised in that context. All coroutines need to be "awaited"; asyncio.run_until_complete() will do that implicitly for you, but run_forever() can't, since it is supposed to run, well, forever. Here's an example how you can see the exception (using Python 3.5 syntax):

>>> 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!