Detect script exit in Python
Python is a scripting language. This means that a Python code is executed line by line with the help of a Python interpreter. When a python interpreter encounters an end-of-file character, it is unable to retrieve any data from the script. This EOF(end-of-file) character is the same as the EOF that informs the end of the file while reading data from a file in Python.
To detect a script exit, we can use the built-in the atexit library of Python. The atexit module is used to register or unregister functions that handle clean-up. The functions that are registered by atexit are automatically called at interpreter termination.
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.
The following example demonstrates how atexit can be used to detect script exit:
- Python3
Python3
import atexit n = 2 print ( "Value of n:" ,n) atexit.register( print , "Exiting Python Script!" ) |
Output:
Value of n: 2 Exiting Python Script!
In this simple program, we passed a print function and a string as arguments to atexit.register function. This registered the print statement as a function that will be invoked on script termination.
We can also use register() method as a decorator.
- Python3
Python3
import atexit n = 2 print ( "Value of n:" ,n) # Using register() as a decorator @atexit .register def goodbye(): print ( "Exiting Python Script!" ) |
Output:
Value of n: 2 Exiting Python Script!
Python provides various functions that can be used to exit a python script, you can check them here.