[Python-Dev] Should asyncio ignore KeyboardInterrupt?

Terry Reedy tjreedy at udel.edu
Sat Jul 4 09:54:20 CEST 2015


Should the loop.run... methods of asyncio respect KeyboardInterrupt (^C)?

Developer and user convenience and this paragraph in PEP

"However, exceptions deriving only from BaseException are typically not 
caught, and will usually cause the program to terminate with a 
traceback. In some cases they are caught and re-raised. (Examples of 
this category include KeyboardInterrupt and SystemExit ; it is usually 
unwise to treat these the same as most other exceptions.) "

and this examples in the doc (two places)

TCP echo server
     # Serve requests until CTRL+c is pressed
     print('Serving on {}'.format(server.sockets[0].getsockname()))
     try:
         loop.run_forever()
     except KeyboardInterrupt:
         pass

suggest yes.  On the other hand, the section on
"Set signal handlers for SIGINT and SIGTERM"
suggests not, unless an explicit handler is registered and then only on 
Unix.

In any case, Adam Bartos, python-list, "An asyncio example", today asks.
'''
This is a minimal example:

import asyncio

async def wait():
     await asyncio.sleep(5)

loop = asyncio.get_event_loop()
loop.run_until_complete(wait())

Ctrl-C doesn't interrupt the waiting, instead KeyboardInterrupt occurs 
after those five seconds. It's 3.5.0b2 on Windows. Is it a bug?
'''

Using run_forever instead, I found no way to stop other than killing the 
process (Idle or Command Prompt).

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list