Python - how to determine when a user closes a console application using the X button

I currently have a python console program running under windows. The program saves most of its data in memory and periodically saves data to disk or when the user disconnects the application through the keyboard interrupt event ( Ctrl + C ).

The problem is that when the user clicks the "X" button in the upper right corner of the console window, the session closes and data in memory is lost. What I'm looking for is an event / signal or hook so that I can clear the memory before closing.

I hope to do this without any external libraries, although if this is not possible, I would still like to know how to do this.

+4
source share
1 answer

In the windows

if you use pywin32, you can execute the event before closing the console, I'm not sure if this will tell you who or what closes it, but maybe this will help you halfway. You can also check: Prevent closing the console application ...

import atexit, os atexit.register(lambda: os.system("pause")) 

For those who encounter this and use Linux ...

when the session / SSH window is closed, the SIGHUP signal is called (the signal freezes).

 import signal signal.signal( signal.SIGHUP, handler ) def handler(signum, frame): #this is called when the terminal session is closed #do logic before program closes pass 
+3
source

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


All Articles