So, I have a script that needs to "clean up" when it is exited: it needs to clear a special logging file and other small things that affect the next startup of the script. The script has a GUI written in Tkinter, if that is relevant at all.

Is there any way to run some "cleanup code" regardless of how the script is exited?

Thanks in advance.

Something like this ...

from Tkinter import *

def exit():
    # do cleanup code here
    pass

root = Tk()
# respond to window title bar  x click
root.protocol("WM_DELETE_WINDOW", exit)

root.mainloop()

You should also read the documentation of the standard lib module atexit which gives example of how you can register functions to be executed at program termination.

Thanks for the solutions guys. They solved my problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.