Open In App
Related Articles

Why does Python automatically exit a script when it’s done?

Like Article
Save Article
Report issue

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.


a = int(input("Enter number: "))
#  waiting for user input...
print("Twice of the number: ", 2 * a)


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:

Exiting Python Script

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.


import atexit
a = 5
print("Twice of a:", a*2)
atexit.register(print, "Exiting Python Script")



Twice of a: 10
Exiting Python Script

Last Updated : 26 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads