Taking signal from terminal close event in Python

How can I make a python script that runs only through the terminal (without a GUI) so as not to exit when the red X is pressed from above, but assign a function to this signal that will eventually close the window and the process (something like a warning dialog box when output, but based on the terminal)?

+3
source share
1 answer

In general, you can use the module atexitto register functions that will be called upon exit:

try:
    _count = int(open("/tmp/counter").read())
except IOError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    open("/tmp/counter", "w").write("%d" % _count)

import atexit
atexit.register(savecounter)

Of course, the user can always forcefully leave your process, and you cannot do anything about it!

+1
source

All Articles