35. Python's atexit Module
The atexit module in Python allows you to register functions to be executed when the Python interpreter terminates, either due to normal exit or due to a call to sys.exit(). These functions can perform cleanup operations such as saving data or closing resources before the program exits.
Here are a few Python code snippets that demonstrate how to use the atexit module:
1. Basic Usage of atexit
import atexit
def goodbye():
print("Goodbye! The program is exiting.")
# Register the function to be called at exit
atexit.register(goodbye)
print("Program is running.")
# The goodbye function will be called when the program exits.2. Multiple Exit Functions
You can register multiple functions with atexit, and they will be executed in the reverse order of their registration.
import atexit
def first_exit_function():
print("First exit function.")
def second_exit_function():
print("Second exit function.")
# Register both functions
atexit.register(first_exit_function)
atexit.register(second_exit_function)
print("Program is running.")
# Both functions will be called in reverse order of registration.3. Using atexit with Arguments
You can pass arguments to the function registered with atexit.
4. Handling Cleanup of Resources
This example demonstrates how you can use atexit to clean up resources like closing files or database connections before exiting.
5. Registering Exit Functions in Classes
You can also use atexit within classes to handle cleanup for instances.
6. Exit Function with Exception Handling
You can also ensure that your exit function handles any exceptions that may arise during execution.
7. Using atexit in Multithreading
atexit works in multithreading, but exit functions are run only once when the program exits.
8. Canceling a Registered Exit Function
If needed, you can remove a previously registered exit function using atexit.unregister.
9. Using atexit in Interactive Environments
In an interactive environment, such as an IPython shell, you can register exit functions that will run when the shell exits.
10. Graceful Shutdown on Program Exit
You can use atexit to perform a graceful shutdown for applications that need to finish processing before they exit.
These examples illustrate how atexit can be useful for performing cleanup operations, managing resources, and ensuring graceful program shutdowns before Python terminates the program.
Last updated