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!
source
share