A shutdown hook is basically a code snippet that allows programmers to run some code at program termination. I had discussed shutdown hook in Java some time back. In this post we will see shutdown hooks in python.
Adding shutdown hook in python using atexit module
You can use the atexit module in python to register shutdown hooks. See the following code
import atexit print("Starting Test Python Module"); def testmethod(): print("From test method") atexit.register(testmethod) print("Terminating Test Python Module");
Save it in a file called test.py and simply run it using
- python test.py
And this outputs :
- Previously you could do the same by importing sys module and then using sys.exitfunc = testmethod but sys.exitfunc is deprecated since python 2.4 and is removed since python 3.0.
- The atexit module defines a single function to register 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 register A, B, and C, at interpreter termination time they will be run in the order C, B, A.
- The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.