Python Program Exit handlers (atexit)


The atexit module in the standard distribution of Python has two functions – register() and unregister(). Both functions take some existing function as an argument. Registered functions are executed automatically when the interpreter session is terminated normally.

If more than one functions are registered, their execution is in the reverse order of registration. It means, functions f1(), f2() and f3() are registered one after other, their order of execution will be f3(), f2() and f1().

The unregister() function removes the specified function from list of functions to be automatically invoked.

Following code shows how a function is registered for automatic execution upon termination of code. (Note: This code has to be executed from a command line and not through IDLE). The program asks a user to input numbers successively and adds them. When the loop is over, the registered function savetotal() is called automatically to save the addition to a file.

import atexit
sum = 0
def savetotal():
fo = open("atexit.txt","w")
fo.write(str(sum))
print ("sum written to file")
fo.close()
atexit.register(savetotal)
while True:
n = int(input("enter a number. -1 to exit"))
if n == -1:
break
sum = sum + n
print (sum)

Save above code as atexit-example.py and run from command line. Successive numbers input are added and the total is written to atexit.txt at the end.

C:\python36>python atexit-example.py
enter a number. -1 to exit4
enter a number. -1 to exit6
enter a number. -1 to exit3
enter a number. -1 to exit5
enter a number. -1 to exit2
enter a number. -1 to exit-1
20
sum written to file

The atexit.txt file will be created in current directory and it will store the total (20 in this case).

It is also possible to register a function with different arguments. In that case, function with each argument will be registered independently and will be executed in reverse order of registration.

import atexit
names = ['Ashok', 'Radha', 'Abdul', 'John']
def hello(name):
print ("Hello",name)
for name in names:
atexit.register(hello,name)

Output

C:\python36>python atexit-example2.py
Hello John
Hello Abdul
Hello Radha
Hello Ashok

atexit.unregister(hello) will remove all copies of hello() with various parameters from the list of functions.

Decorator syntax

A convenient alternative to register a function is to use register() function as a decorator.

import atexit
@atexit.register
def hello():
print('Hello World!')
print('Say Hello')

Output

C:\python36>python atexit-example3.py
Say Hello
Hello World!

The registered functions will not be invoked automatically if program terminates abruptly or os.exit() function is called.

The atexit module is useful in automatically performing clean operations like closing databases and files, freeing up resources etc.

Updated on: 27-Jun-2020

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements