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)?
-
What OS? What platform? You want to modify the close event behaviour of your terminal?– CppLearnerCommented Apr 14, 2012 at 18:34
-
I want to do this on Windows, it is added as a tag.– Serban RazvanCommented Apr 14, 2012 at 18:35
-
Did the answer you accepted actually work for you on Windows?– Matt JoinerCommented Dec 11, 2013 at 5:37
Add a comment
|
1 Answer
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!
-
1Clicking the red X on windows terminal is not firing atexit :( Commented Dec 5, 2013 at 22:52
-
1I 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.– KatrielCommented Dec 11, 2013 at 12:31