Asyncio loop add_signal_handler () on Windows

I am currently migrating a Python project from Linux to Windows (using Anaconda Python 3.6). Everything works fine, I just can't get a graceful exit from the asyncio loop.

On Linux, I do 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() 

On Windows, unfortunately, I get a NotImplementedError on add_signal_handler . Without this, of course, I never get a chance to finish the program cleanly.

Any ideas on how to solve this? Thanks.

+5
source share
1 answer

There are no signals in Windows.

If the process is destroyed through the TerminateProcess API, you will not have any possibility to clean it up (for example, "kill -9", will delete your process).

But Windows has two ways to indicate whether 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 throws a KeyboardInterrupt exception, but you can connect your own code to this handler using the console handler APIs ( https://docs.microsoft.com/en-us/windows/console/console-control- handlers ), but this is probably bust. Just install the correct exception handler in the event loop.

For processes with a graphical interface, Windows sends you Windows messages, such as WM_QUIT or others, if the user logs out, the system enters energy saving mode, etc., you can also deal with them using ctypes or the win32 package or any of a variety of python gui libs.

+3
source

Source: https://habr.com/ru/post/1271398/


All Articles