I have this really small test program which does nothing apart from a executing an asyncio
event loop:
import asyncio asyncio.get_event_loop().run_forever()
When I run this program on Linux and press Ctrl+C, the program will terminate correctly with a KeyboardInterrupt
exception. On Windows pressing Ctrl+C does nothing (tested with Python 3.4.2). A simple inifinite loop with time.sleep()
raises the KeyboardInterrupt
correctly even on Windows:
import time while True: time.sleep(3600)
Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows?
Deep inside asyncio, we have an event loop. An event loop of tasks. The event loop's job is to call tasks every time they are ready and coordinate all that effort into one single working machine. The IO part of the event loop is built upon a single crucial function called select .
Run an asyncio Event Loop run_until_complete(<some Future object>) – this function runs a given Future object, usually a coroutine defined by the async / await pattern, until it's complete. run_forever() – this function runs the loop forever. stop() – the stop function stops a running loop.
There is workaround for Windows. Run another corouting which wake up loop every second and allow loop to react on keyboard interrupt
Example with Echo server from asyncio doc
async def wakeup(): while True: await asyncio.sleep(1) loop = asyncio.get_event_loop() coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888) server = loop.run_until_complete(coro) # add wakeup HACK loop.create_task(wakeup()) try: loop.run_forever() except KeyboardInterrupt: pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With