Issue 26455: Inconsistent behavior with KeyboardInterrupt and asyncio futures (original) (raw)
If you trigger KeyboardInterrupt in a coroutine and catch it, the program terminates cleanly:
import asyncio
async def bar(): raise KeyboardInterrupt
loop = asyncio.get_event_loop()
try: loop.run_until_complete(bar()) except KeyboardInterrupt: print("It's ok") finally: loop.stop() loop.close()
This outputs:
It's ok
However, if you wrap the coroutine in a Task, you will get a mixed behavior:
try: task = asyncio.ensure_future(bar()) loop.run_until_complete(task) except KeyboardInterrupt: print("It's ok")
This outputs:
It's ok Task exception was never retrieved future: <Task finished coro=<bar() done, defined at ki_bug.py:4> exception=KeyboardInterrupt()> Traceback (most recent call last): File "ki_bug.py", line 10, in loop.run_until_complete(main_future) File "/usr/lib/python3.5/asyncio/base_events.py", line 325, in run_until_complete self.run_forever() File "/usr/lib/python3.5/asyncio/base_events.py", line 295, in run_forever self._run_once() File "/usr/lib/python3.5/asyncio/base_events.py", line 1258, in _run_once handle._run() File "/usr/lib/python3.5/asyncio/events.py", line 125, in _run self._callback(*self._args) File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step result = coro.send(None) File "ki_bug.py", line 5, in bar raise KeyboardInterrupt KeyboardInterrupt
We have several contradictory behaviors: the KeyboardInterrupt is raised, and captured by the future (since your can do task.exception() to suppress the stracktrace) but also catched by except while the program is allowed to continue, yet still the stack trace is displayed and eventually the program return code will be 0.
It's very confusing.
python/asyncio is archived now and there is no definitive resolution, nor a concrete workaround in that thread. has this progressed elsewhere? or is it still unresolved?
could anyone please show sample workaround code? (i need to call some cleanup code which still runs in the context of the event loop)
also, I was unable to login to this bug tracker with GitHub, because my name contains non-ascii characters. where should I report that :D ?