Published: 2022-07-05.
The module atexit allows registering hooks that will be executed when the program terminates.
There are only a few cases when it is NOT executed:
os._exit
(don’t confuse with sys.exit
) is called.In all other cases, like an unhandled exception or sys.exit
, the registered hooks will be executed.
A few use cases:
However, keep in mind that there is no way to handle unhandled exceptions using atexit
because it is executed after the exception is printed and discarded.
import atexit
atexit.register(print, 'FINISHED')
1/0
Output:
Traceback (most recent call last):
File "example.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
FINISHED