How to Exit a Python script? - GeeksforGeeks

03 Jan, 2021
Exiting a Python script refers to the process of termination of an active python process. In a more practical way, it is generally a call to a function (or destructor) exit routines of the program. This process is done implicitly every time a python script completes execution (or runs out of executable code), but could also be invoked by using certain functions. 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.
There exist several ways of exiting a python application. The following article has explained some of them in great detail. A thorough read of it would educate the users on when to use which method, and which one is the most suitable for their particular use case. In general, their functionality is more or less the same which is to exit the python program. Some functions do that properly (calling cleanup routines, flushing buffers, closing file objects, etc.) and others do it brutally (without the aforementioned steps). It is often better to use in-built methods because they are just required to be called where ever needed.
Example:
Python3
print("this is the first statement")  exit()  print("this is the second statement")
Output:
this is the first statement
Sometimes it is required to perform certain tasks before the python script is terminated. 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 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.   
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.  
Example:
Python3
import atexit    def exit_handler():    print('My application is ending!')    atexit.register(exit_handler)  print('GFG!')
Output:
GFG
My application is ending!
Sometimes we are interested just in the execution or termination of the program rather than any errors encountered therein. This is possible if we are able to catch any exceptions or errors that are encountered during the execution. This is made possible by utilizing the except: clause found inside a generic try-except block. We would be making use of the fact that a bare except can catch not only exceptions but even certain interrupts and errors encountered during the execution of the try block.  
A bare except clause is generally not advisable in practical code. The reason is that it conceals several types of errors produced during the code as well. This behavior may make debugging the code a little hectic. Therefore, it should be used with caution and only when the code in try clause isn’t error prone (which isn’t a plausible assumption in most cases). 
Example:
Python3
def main():    asdfgh    print("HELLO WORLD!")    if __name__ == "__main__":    try:        main()      except:        print("Gotcha!")
Output:
Gotcha!
Generally, when a python program encounters an error it displays it on the console screen. But sometimes we are interested in exiting the application while displaying some text denoting a possible error which might have occurred. This process could also be used to exit the program and display some text at the end.  In the following code we will be exiting the python program after displaying some text.
Here a string or an integer could be provided as an argument to the exit() function. If the argument is a string (denoting an error msg etc), then it will be outputted after program execution. If it is an integer then it should be an POSIX exit code.   
Example:
Python3
print("Hello world!")  exit("__PUT_ERROR_MSG_HERE__")
Output:
Hello world!
__PUT_ERROR_MSG_HERE__
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()