188

How can you have a function or something that will be executed before your program quits? I have a script that will be constantly running in the background, and I need it to save some data to a file before it exits. Is there a standard way of doing this?

1
  • 2
    The script shouldn't ever stop, but maybe someone will kill the process or press Ctrl+\ or something.
    – RacecaR
    Commented Oct 3, 2010 at 15:11

7 Answers 7

289

Check out the atexit module:

http://docs.python.org/library/atexit.html

For example, if I wanted to print a message when my application was terminating:

import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)

Just be aware that this works great for normal termination of the script, but it won't get called in all cases (e.g. fatal internal errors).

11
  • 11
    Is there any way to make it where it will be called if you press Ctrl+C or Ctrl+\?
    – RacecaR
    Commented Oct 3, 2010 at 15:08
  • 14
    It will be called if you press Ctrl+C. That simply raises a KeyboardInterrupt exception. Commented Oct 3, 2010 at 15:11
  • 1
    Oh, I forgot that. And I assume that nothing you can do will be run if somebody kills the python process right?
    – RacecaR
    Commented Oct 3, 2010 at 15:11
  • 6
    @RacecaR: indeed; the point of killing a process is to stop it dead. From the docs: Note The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.
    – Katriel
    Commented Oct 3, 2010 at 15:12
  • 34
    @RacecaR, the only way you can run termination code even if a process badly crashes or is brutally killed is in another process, known as a "monitor" or "watchdog", whose only job is to keep an eye on the target process and run the termination code when apropriate. Of course that requires a very different architecture and has its limitations; if you need such functionality it's best for you to open a different Q on the matter. Commented Oct 3, 2010 at 15:18
49

If you want something to always run, even on errors, use try: finally: like this -

def main():
    try:
        execute_app()
    finally:
        handle_cleanup()

if __name__=='__main__':
    main()

If you want to also handle exceptions you can insert an except: before the finally:

1
  • 28
    Doesn`t work when SIGTERM occurs due to killing of the process.
    – ramu
    Commented Aug 19, 2015 at 0:31
29

If you stop the script by raising a KeyboardInterrupt (e.g. by pressing Ctrl-C), you can catch that just as a standard exception. You can also catch SystemExit in the same way.

try:
    ...
except KeyboardInterrupt:
    # clean up
    raise

I mention this just so that you know about it; the 'right' way to do this is the atexit module mentioned above.

1
  • if you want the script from raising KeyboardInterrupt, why are you calling raise? Commented Oct 31, 2023 at 0:17
9

This is a version adapted from other answers. It should work (not fully tested) with graceful exits, kills, and PyCharm stop button (the last one I can confirm).

import signal
import atexit


def handle_exit(*args):
    try:
        ... do computation ...
    except BaseException as exception:
        ... handle the exception ...


atexit.register(handle_exit)
signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)
1
  • unless handle_exit calls sys.exit or something, then the signal handlers won't cause your program to exit like most people expect it to do when they hit ctrl-c or run the 'kill' command. See this answer for a solution to that: stackoverflow.com/a/75732683/13576614 Commented Oct 31, 2023 at 0:16
7

This can handle normal exit as well as killing the process with kill or Ctrl+C:

import sys
import atexit
import signal

def exit_handler():
    print("Cleaning up")

def kill_handler(*args):
    sys.exit(0)

atexit.register(exit_handler)
signal.signal(signal.SIGINT, kill_handler)
signal.signal(signal.SIGTERM, kill_handler)

# MAIN PROGRAM
# for example just reading from the input:
input("Press enter: ")

2
  • 2
    I like this one. The kill_handler doesn't have to call exit_handler because handling the signals gives atexit a chance to do its thing. Commented Oct 31, 2023 at 0:14
  • 1
    Yes, it works equally well when program finishes normally or when it killed with kill or Ctrl+C (added this to the answer)
    – Alek
    Commented Nov 5, 2023 at 16:37
4

If you have class objects, that exists during the whole lifetime of the program, you can also execute commands from the classes with the __del__(self) method:

class x:
def __init__(self):
    while True:
        print ("running")
        sleep(1)

def __del__(self):
    print("destructuring")


a = x()

this works on normal program end as well if the execution is aborted, for sure there will be some exceptions:

running
running
running
running
running
Traceback (most recent call last):
  File "x.py", line 14, in <module>
    a = x()
  File "x.py", line 8, in __init__
    sleep(1)
KeyboardInterrupt
destructuring
1
  • you should almost never expect a class's del function to get called on your program exits. This is not the proper way to handle at exit program behavior. The behavior is non-deterministic and will not function properly as you expect. see here @Rastefan
    – baymurat
    Commented Nov 28, 2023 at 9:22
0

You could also use a context manager to do something similar to @Brian C. Lane's answer :

from contextlib import closing


class RunThat:
    def __init__(self) -> None:
        pass

    def execute_app(self) -> None:
        print("computation")

    def close(self) -> None:
        print("handle_cleanup")


with closing(RunThat()) as rt:
    rt.execute_app()

# --- which results in
# computation
# handle_cleanup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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