Python Exit handlers: atexit
In this tutorial, you will learn about Exit handlers in Python. Python Exit handlers: atexit module as two functions namely register() and unregister(). These are functions that execute at the time of normal interpreter termination. During abnormal termination, these functions will not be executed. In other words, registered functions not executed during signal losses, internal errors, and usage of os.exit().
Exit handlers : atexit.register()
register() takes function and function’s arguments as its arguments. We can pass the same function with different arguments more than once. At the time of termination of an interpreter, all functions registered with atexit are executed.
import atexit def ending(n): print('bye %s' %(n)) atexit.register(ending,"Codespeedy")
bye Codespeedy
Functions are stored in the stack according to their registering order. So, when you give more than two functions they execute in LAST IN FIRST OUT manner. So, assign functions in reverse order to get output in sequence.
import atexit def f1(): print(1) def f2(): print(2) atexit.register(f1) atexit.register(f2)
2 1
Using atexit as a decorator
import atexit @atexit.register def bye(): print("bye")
bye
All functions assigned should not return any value.
atexit.unregister()
When we want some registered function to not execute at the termination unregister() is used. Even though function registered more than once unregister() stops the function from execution at the time of the interpreter termination.
import atexit def f1(): print(1) def f2(): print(2) atexit.register(f1) atexit.register(f2) atexit.unregister(f1)
2
Python is a mighty and useful programming language. Because of its open-source nature, we have a vast, number of libraries available for making our work simple and fast. Python Exit handlers: The atexit module is one such module that makes registering and unregistering of methods easier. With the help of this module, you can implement at termination time, and you can also stop methods from executing at termination.
To learn how to use NumPy. empty go here: Python numpy.empty() function
Leave a Reply