How to Exit a Python script?
Last Updated :
07 Dec, 2023
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.
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.
Exit using Python Exit() Method
In this example, we will see How to Use the exit()
Function in Python. The "exit()" statement terminates the program immediately, preventing the execution of any subsequent code. Therefore, the "print("this is the second statement")" line is never reached.
Python3
print("this is the first statement")
exit()
print("this is the second statement")
Output:
this is the first statement
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!
Exit without errors
Sometimes to terminate a code block, and it's related process, we raise errors. These errors can be handled on the calling function side. Here, we have raised a SyntaxError with custom error message to terminal the code. The try...except block handles the error and terminates the code normally.
Using explicitly raised errors to terminate a process
In the given example, the `main` function intentionally raises a custom `SyntaxError`. The `try-except` block in the `__main__` section catches the specific `SyntaxError` raised by the `main` function, and prints "We caught the error!" as a response.
Python3
def main():
raise SyntaxError("Custom Syntax Error")
if __name__ == "__main__":
try:
main()
except SyntaxError:
print("We caught the error!")
Output:
We caught the error!
Exit with Error Messages
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 message etc.), then it will be outputted after program execution. If it is an integer, then it should be an POSIX exit code.
Exiting Python code with custom error message
In this example the below code prints "Hello world!" to the console and then exits with an error message "__PUT_ERROR_MSG_HERE__".
Python3
print("Hello world!")
exit("__PUT_ERROR_MSG_HERE__")
Output:
Hello world!
__PUT_ERROR_MSG_HERE__
Similar Reads
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
2 min read
How to Exit a Python Program in the Terminal Exiting a Python program might seem like a straightforward task, but there are several ways to do it depending on the context and requirements of your script. Whether you want to gracefully shut down your application or terminate it immediately, knowing the right approach can help you manage your co
3 min read
How to Execute a Python Script from the Django Shell? The Django shell is an interactive development and scripting environment that aids us in working with our Django project while experiencing it as if it were deployed already. It is most commonly used when one has to debug, test, or carry out one-time operations that require interaction with the Djan
4 min read
How to Exit When Errors Occur in Bash Scripts When writing Bash scripts, it's essential to include error handling to ensure that the script exits gracefully in the event of an error. In this article, we'll cover all the possible techniques for exiting when errors occur in Bash scripts, including the use of exit codes, the "set -e" option, the "
7 min read
How to terminate execution of a script in PHP ? In this article, we are going to discuss how to terminate the execution of a PHP script. In PHP, a coder can terminate the execution of a script by specifying a method/function called the exit() method in a script. Even if the exit() function is called, the shutdown functions and object destructors
2 min read