Member-only story
How to Create Exit Handlers for Your Python App
Utilizing atexit, a Python module to register functions to be called when a program closes down normally
By reading this piece, you will learn how to define your own exit handlers that will be executed when you quit your Python application. Based on the official documentation:
“The
atexit
module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.atexit
runs these functions in the reverse order in which they were registered; if you registerA
,B
, andC
, at interpreter termination time they will be run in the orderC
,B
,A
.”
This module is extremely useful if you are looking for a way to clean up the resources and shut down unnecessary connections gracefully upon exiting your application. However, please bear in mind that the registered functions will not be called under the following circumstances:
- When the program is killed by a signal not handled by Python.
- When a Python fatal internal error is detected.
- When
os._exit()
is called.
Let’s proceed to the next section and begin writing some Python code.
Implementation
The atexit
module is part of the built-in module in Python and does not require any further installation. If you are using Python version 3.7 or a more recent version, registered functions are local to the interpreter they were registered in when used with C-API sub-interpreters.
Simple example
Add the following import declaration in your Python file:
import atexit
Define your own function that will be called when the application quits. I am going to use a simple print
statement as a demonstration. This will be the part where you input the code to clean up the resources and close any existing connections to the database:
def OnExitApp():
print("Exit Python application")
The next step is to register your function:
atexit.register(OnExitApp)