- How to Exit a Python script?
- Exiting a Python application
- Example: Exit Using Python exit() Method
- Python3
- Detecting Script exit
- Terminate a Program in Python
- Terminate a Program Using the quit() Function
- Terminate a Program Using the exit() Function
- Terminate a Program Using the sys.exit() Function
- Using the SystemExit exception
- Conclusion
- Related
- Recommended Python Training
- Complete python exit tutorial with examples in 2023
- Types of python exit function
- Python exit() function
- Python exit(0)
- Python exit(1)
- Python quit() function
- Python sys.exit() function
- python os._exit() function
- Python exit vs quit
- Python exit with an error
- Python exit from a program gracefully
- Conclusion
How to Exit a Python script?
Exiting a Python script refers to the process of 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 a python application. The following article has explained some of them in great detail.
Example: Exit Using Python exit() Method
Python3
this is the first statement
Detecting Script exit
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 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.
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.
Terminate a Program in Python
While writing a program in python, you might need to end a program on several occasions after a condition is met. In this article, we will discuss different ways to terminate a program in python.
Terminate a Program Using the quit() Function
The quit() function is an inbuilt function that you can use to terminate a program in python. When the quit() function is executed, it raises the SystemExit exception. This results in the termination of the program. You can observe this in the following example.
number = 10 if number >= 10: print("The number is:", number) quit() print("This line will not be printed")
The quit() function is defined in the site module and it works only if the module is installed. Therefore, I would recommend you not to use this function in real-world applications. However, you can use the quit() function while writing smaller programs.
Terminate a Program Using the exit() Function
The exit() function is also defined in the site module. It works in a similar way to the quit() function and terminates the program when executed as shown in the following example.
number = 10 if number >= 10: print("The number is:", number) exit() print("This line will not be printed")
Again, I would advise you to not use this function in the production environment due to its module dependency.
Terminate a Program Using the sys.exit() Function
The sys module is included in the core python installation. You can import the sys module as follows.
To terminate a program using the sys module, we will use the sys.exit() function. The sys.exit() function when executed, takes a string message as the optional input argument and prints the message before terminating the program as shown below.
import sys number = 10 if number >= 10: print("The number is:", number) sys.exit() print("This line will not be printed")
However, passing any input argument other than 0 means that the program has an abnormal termination.
Using the SystemExit exception
All the above functions raise the SystemExit exception to terminate the program. So, we can also raise the SystemExit program explicitly to terminate a program in python as follows.
import sys number = 10 if number >= 10: print("The number is:", number) raise SystemExit print("This line will not be printed")
Conclusion
In this article, we have seen different ways to terminate a program in python. The best way to terminate a program is to use the sys.exit() function as discussed by many people on StackOverflow. So, I would suggest you use this function to terminate a program. To learn more about python programming, you can read this article on list comprehension. You might also like this article on string concatenation in python.
Related
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
Complete python exit tutorial with examples in 2023
Python provides many exit functions using which a user can exit the python program. In this blog, we will learn everything about the python exit function. So let’s get started.
Types of python exit function
Python mainly provides four commands using which you can exit from the program and stop the script execution at a certain time. The 4 types of exit commands are:-
Python exit() function
The python exit() function is available in the site module. It is used for the exit or termination of a Python script. The exit command should not be used in production and can only be used for interpreters. Below is the sample python code with the exit function.
This gives the below output:
You can also use exit() with an argument which is the exit code, for example:
Python exit(0)
In Python, the exit(0) function is used to exit or terminate a Python script and return an exit code of 0. The exit code 0 is a standard convention to indicate that the program has terminated without errors. Below is the sample python code for exit(0)
Please note that you can also use exit() with no arguments, which is equivalent to calling sys.exit(0)
Python exit(1)
In Python, the exit(1) function is used to exit or terminate a Python script and return an exit code of 1. Exit code 1 indicates an unsuccessful termination or an error occurred during the execution of the script. Below is the sample python code for exit(1)
age = 45 if age < 50: # exit the program print(exit) exit(1)
Please note that the exit code of 1 is just a convention and you can use any other integer value to indicate different types of errors.
Python quit() function
In Python, the quit() function is equivalent to the exit() function. However, the quit() function is only available n python2 but not in python 3.Quit() function should only be used in the interpreter. Below is the sample python code which uses the quit() function.
age = 45 if age < 50: # quit the program print(quit) quit()
The above code defines a variable age as 45 and then checks if the value of age is less than 50. If it is, it will print the value of the quit function and then call the quit() function to stop the program from running.
Python sys.exit() function
In Python, the sys.exit() function is used to exit or terminate a Python script. The sys.exit() function can be used in production because it raises an SystemExit exception that causes the interpreter to exit. You can use the sys.exit() program with or without arguments. With an argument, the program will exit and return a successful exit code on 0, whereas with an argument, which is the exit code like:
import sys for i in range(1,5): print(i) if i == 3: sys.exit()
The above code will print the numbers from 1 to 3, and then the sys.exit() function will be called when the value of i is 3. This will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination.
python os._exit() function
In Python, the os._exit() function is used to immediately exit the current process without performing any cleanup or finalization tasks. The os._exit() does not call any cleanup handlers, close open files, or flush stdio buffers. This can make it more efficient for exiting a program, but it also means that any necessary cleanup or finalization tasks will not be executed. It is important to consider the use of os._exit() as it may leave resources open and could cause issues when running in a multi-threaded environment.
Below is the sample python code using the os._exit() function
import os for i in range(1,5): print(i) if i == 3: os._exit(0)
After the number 3 is printed, the os._exit(0) function will be called, causing the script to immediately terminate and exit the process without printing the remaining numbers (4) in the range.
Python exit vs quit
In Python, the exit() function and quit() function are used to terminate a Python script. Both these functions raise a SystemExit exception, which causes any finally clauses in a try/finally statements to be executed and any unhandled exceptions to be logged.
exit() is a built-in function in both Python2 and Python3, while quit() is a built-in function only in Python2. In Python3 and it is recommended to use exit() or sys.exit() instead.
It’s important to ensure that any resources which the program uses, like file handlers, sockets, or database connections, are closed correctly before exiting the program using exit() or quit() with a non-zero exit code.
Python exit with an error
In Python, you can use the sys.exit() function with a non-zero exit code to exit the program and indicate that an error has occurred. For example:
import sys for i in range(1,5): if i == 3: sys.exit("Exiting,as number is equal to 3 ") print(i)
In the above code, the script will print the numbers from 1 to 2 and then exit the program when the value of i is 3. The sys.exit() function will be called, which will cause the script to terminate and end the program with an exit code of 0, indicating a successful termination. The message “Exiting, as number is equal to 3” will also be printed before the script exits.
Python exit from a program gracefully
Exiting a program gracefully refers to allowing the program to perform any necessary cleanup or finalization tasks before terminating. In Python, you can exit a program gracefully by using the sys.exit() function along with finally block to handle any necessary cleanup or finalization tasks.
For example, Below is the sample try-finally block to perform cleanup tasks before exiting the program:
def test(): try: # code to run finally: # cleanup tasks print("Cleanup Done") sys.exit(0) if __name__ == "__main__": test()
Conclusion
I hope you have liked this tutorial on the python exit function. Please do let me know if you need further inputs.