Detecting Script Exit in Python

Sometimes it is required to perform certain tasks before the exit python script. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has been executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code.   

Detecting Code Exit Events using Atexit Module

In the following code, we would be defining (and registering) a function that would be called upon the termination of the program. First, the atexit module is imported. Then exit_handler() function is defined. This function contains a print statement. Later, this function is registered by passing the function object to the atexit.register() function. In the end, there is a call to print function for displaying GFG! in the output. In the output, the first line is the output of the last print statement in the code. The second line contains the output of exit_handler function that is called upon the code execution (as a cleanup function).  

Not all kinds of exits are handled by the atexit module.

Python3




import atexit
 
def exit_handler():
    print('My application is ending!')
 
atexit.register(exit_handler)
print('GFG!')


Output:

GFG
My application is ending!

How to Exit a Python script?

In this article, we are going to see How to Exit Python Script.

Exiting a Python script refers to the termination of an active Python process. In this article, we will take a look at exiting a Python program, performing a task before exiting the program, and exiting the program while displaying a custom (error) message.

Similar Reads

Exiting a Python Application

There exist several ways of exiting Python script applications, and the following article provides detailed explanations of several such approaches How to exit Python script....

Detecting Script Exit in Python

...

Exit without errors

Sometimes it is required to perform certain tasks before the exit python script. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has been executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code....

Exit with Error Messages

...