Reading Time: 1 minutes
Call functions upon termination of program in Python
The builtin module atexit helps to call functions upon normal termination of Python scripts. This is achieved using its register() function.
# Contents of testAtExit.py
import atexit
def bye():
print("Goodbye...")
atexit.register(bye)
# Command prompt / Terminal
$ python path_to_testAtExit.py
Goodbye...
Python allows to register more than one functions, and to pass arguments to these functions.
# Contents of testAtExit.py
import atexit
def bye(name):
print("Goodbye {}...".format(name))
atexit.register(bye, 'Ethan')
# Command prompt / Terminal
$ python path_to_testAtExit.py
Goodbye Ethan...
Note that registered functions are not called in the following events:
- When program is exited using os._exit(). The registered functions are called when the program is exited using sys.exit().
- When the program is killed with a signal. This can be done using the subprocess module and kill() function of the os module.







