Python - How to detect when user closes a console application via "X" button -


I currently have a console based Python program running under Windows. This program keeps most of its data in memory and periodically saves data to disk or when the user has a keyboard interrupt ( Ctrl + C ) The application has stopped.

The problem I have is that when a user hits the "X" button at the top right of the console window, the session stops and the data is lost in memory. What I want is an event / signal or hook, so that I can clear the memory before closing.

I hope to do this without any external libraries, though it is not possible I still want to know how it can be done.

in the window

If you are using pywin32, you close the console An event can happen before it happens, I am not sure whether it will tell you who is shutting it down, but it may have shown you half way. You can also check them:

  import atom, OS atexit.register (lambda: OSSystem ("pause"))   

for those Those who come on it and use Linux ...
  The SIGHUP signal is thrown when the import signal signal is off (signal is hanging).     Terminal session closes before the program closes, when it indicates: # Indicator (signal.

Comments