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.
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.
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