In Python, the atextit
module is used to perform clean-up operations on the interpreter termination. This module provides functions similar to shutdown hooks in Java. The
The functions registered via this module are not executed when a program is terminated by a signal that is not handled by Python, when os.exit()
is called, or when Python fatal internal error is detected. Thee handlers or functions are executed in reverse order with reference to the order in which they were registered.
register()
methodThe register()
method registers the given function to be executed at termination. This method also accepts the arguments that need to be passed to the given function.
The given function can also be registered using the @atexit.register
decorator. For example:
@atexit.register
def func_4():
print("Executing func_4 with no arguments")
atexit.register(func, *args, **kwargs)
func
: This is the function to be registered.args
and kwargs
: These are the function arguments.This function returns the called func
. The calling can therefore be traced.
import atexitdef func_1(args):print("Executing func_1 with argument - %s" % (args,))def func_2():print("Executing func_2 with no arguments")def func_3(arg1, arg2):print("Executing func_3 with arg1 - %s, arg2 - %s" % (arg1, arg2))print("Hello Educative")atexit.register(func_1, [1,2,3])atexit.register(func_2)atexit.register(func_3, arg1="hello", arg2="educative")
atexit
module.func_1
, which takes args
as an argument, and we print it.func_2
with no arguments and print a string.func_3
, which takes arg1
and arg2
as arguments, and we print it.print
statement.func_1
as an exit handler using the register
method, where we pass the argument as a positional argument.func_2
as an exit handler using the register
method. As the function accepts no arguments, no parameters are passed as arguments in the register
method.func_3
as an exit handler using the register
method where we pass the arguments as keyword arguments.When we run the code, func_3
is executed first, then func_2
, and finally func_1
is executed.