Why does Python automatically exit a script when it’s done?
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.
There is an EOF character present at the end of each python script that instructs the interpreter to stop the execution of code. While working on a standard input connected to a tty device, we can produce a similar result with CTRL+D on UNIX and CTRL+Z, ENTER on Windows.
Consider this simple code that takes a number as user input and returns twice of that number.
Try pressing the EOF character(depending on your os) while the program is waiting for user input. The program will terminate as soon as it encounters the EOF character like this:
Notice that the program throws an EOFError Exception when it encounters EOF before the program completion.
How to Detect Script Exit?
We can use the atexit module to detect the script exit. The following code detects script exit using register() function of the atexit module.
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 atexit.register() method takes a function as an argument that is to be executed at script exit.
Twice of a: 10 Exiting Python Script