Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asyncio loop's add_signal_handler() in Windows

Tags:

python

windows

I'm currently porting a Python project from Linux to Windows (using Anaconda Python 3.6). Everything works perfectly, I just cannot get a graceful exit of the asyncio loop working.

In Linux I'm doing the following:

class GracefulExit(SystemExit):
    code = 1

def raise_graceful_exit():
    raise GracefulExit()

loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGINT, raise_graceful_exit)
loop.add_signal_handler(signal.SIGTERM, raise_graceful_exit)

try:
    loop.run_forever()
except GracefulExit:
    pass

shutdown()

In Windows, unfortunately I get a NotImplementedError on add_signal_handler. Without this, of course I never get a chance for a clean shutdown of the program.

Any ideas on how to solve this? Thanks.

like image 564
The_Fallen Avatar asked Aug 31 '17 18:08

The_Fallen


1 Answers

Actually you can implement kind of a cross-platform python signal handler in your python script that works on both Unix/Linux and Windows, python has a standard signal library, so you can do something like this

import asyncio
import signal


class GracefulExit(SystemExit):
    code = 1


def raise_graceful_exit(*args):
    loop.stop()
    print("Gracefully shutdown")
    raise GracefulExit()


def do_something():
    while True:
        pass


loop = asyncio.get_event_loop()
signal.signal(signal.SIGINT, raise_graceful_exit)
signal.signal(signal.SIGTERM, raise_graceful_exit)

try:
    loop.run_forever(do_something())
except GracefulExit:
    pass
finally:
    loop.close()

It does not behave exactly the same on Windows and Linux due to the aforementioned platform differences, but for most cases it works okay on both platforms.

like image 50
hellopeach Avatar answered Oct 12 '22 23:10

hellopeach