3

How can I make a python script that is run only through terminal (no GUI) to not quit when the red X at the top is pressed, but to assign a function to that signal which eventually would close the window and the process (something like an alert dialog on exit, but terminal based)?

3
  • What OS? What platform? You want to modify the close event behaviour of your terminal?
    – CppLearner
    Commented Apr 14, 2012 at 18:34
  • I want to do this on Windows, it is added as a tag. Commented Apr 14, 2012 at 18:35
  • Did the answer you accepted actually work for you on Windows? Commented Dec 11, 2013 at 5:37

1 Answer 1

1

In general, you can use the atexit module to register functions to be called on 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 force-quit your process, and you can't do anything about that!

2
  • 1
    Clicking the red X on windows terminal is not firing atexit :( Commented Dec 5, 2013 at 22:52
  • 1
    I don't know what the Windows terminal sends to processes. It's certainly possible that it doesn't send any signal and just kills them, in which case you can't do anything about it.
    – Katriel
    Commented Dec 11, 2013 at 12:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.