This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Michel Desmoulin
Recipients Michel Desmoulin, gvanrossum, vstinner, yselivanov
Date 2016-02-28.19:50:26
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1456689026.99.0.0359024900858.issue26455@psf.upfronthosting.co.za>
In-reply-to
Content
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 <module>
    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.
History
Date User Action Args
2016-02-28 19:50:27Michel Desmoulinsetrecipients: + Michel Desmoulin, gvanrossum, vstinner, yselivanov
2016-02-28 19:50:26Michel Desmoulinsetmessageid: <1456689026.99.0.0359024900858.issue26455@psf.upfronthosting.co.za>
2016-02-28 19:50:26Michel Desmoulinlinkissue26455 messages
2016-02-28 19:50:26Michel Desmoulincreate