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

前端 未结 3 451
醉话见心
醉话见心 2020-12-03 04:49

I have this really small test program which does nothing apart from a executing an asyncio event loop:

import asyncio
asyncio.get_event_loop().r         


        
相关标签:
3条回答
  • 2020-12-03 05:11

    This is a bug, sure.

    See issue on python bug-tracker for the problem solving progress.

    0 讨论(0)
  • 2020-12-03 05:13

    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
    
    0 讨论(0)
  • 2020-12-03 05:28

    If you just want to exit the program and don't need to catch the KeyboardInterrupt, the signal module provides a simpler (and more efficient) workaround:

    # This restores the default Ctrl+C signal handler, which just kills the process
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    
    # Now the event loop is interruptable
    import asyncio
    asyncio.get_event_loop().run_forever()
    
    0 讨论(0)
提交回复
热议问题