Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows?

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?

like image 597
skrause Avatar asked Dec 15 '14 09:12

skrause


People also ask

How does the Asyncio event loop work?

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 .

How do I stop Asyncio from looping events?

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.


1 Answers

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 
like image 141
farincz Avatar answered Sep 21 '22 13:09

farincz