asyncio loop's add_signal_handler() in Windows
Windows does not have signals.
If the process gets killed via the TerminateProcess API, you do not get any chance to cleanup (its like 'kill -9', blows your process away).
But windows has two ways to signal if your code should exit, one for console programs (e.g. python.exe) and one for gui programs (pythonw.exe).
Python automatically handles the console thing and raises a KeyboardInterrupt exception, but you can hook your own code into that handler with the console control handler APIs (https://docs.microsoft.com/en-us/windows/console/console-control-handlers), but thats probably overkill. Just set a proper exception handler on your event loop.
For GUI processes, Windows sends you windows messages, like WM_QUIT or various others if a user logs off, system goes to power saving mode etc., you can handle those too, with the help of ctypes or the win32 package, or any of the many python gui libs.
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.