Open In App

Python Exit handlers (atexit)

atexit is a module in python which contains two functions register() and unregister(). The main role of this module is to perform clean up upon interpreter termination. Functions that are registered are automatically executed upon interpreter termination. Whenever a program is killed by a signal not handled by Python, when os.exit() is called, or Python fatal internal error is detected, the functions registered via this module are not executed.

Syntax: atexit.register(fun, *args, **kwargs) 



Parameters: First the function name is mentioned and then any arguments for that function is passed. The parameters are separated using ‘, ‘. 

Return: This function returns the called fun and hence the calling can be traced.



# Example 1: 




# Python program to demonstrate
# atexit module
 
 
import atexit
 
names = ['Geeks', 'for', 'Geeks']
 
def hello(name):
    print (name)
 
for name in names:
 
    # Using register()
    atexit.register(hello, name)

Output :

Geeks
for
Geeks

# Example 2: Using register as a decorator 




# Python program to demonstrate
# atexit module
 
 
import atexit
 
# Using register() as a decorator
@atexit.register
def goodbye():
    print("GoodBye.")

Output :

GoodBye.

Syntax: atexit.unregister(fun) 

Parameters: The function may or may not contain any parameter. If any present then the fun name is to be specified. 

Return: No return.

Example: 




# Python program to demonstrate
# atexit module
 
 
import atexit
 
names = ['Geeks', 'for', 'Geeks']
 
def hello(name):
    print (name)
 
for name in names:
 
    # Using unregister()
    atexit.unregister(hello)

Output :

No Output

Article Tags :