It is necessary to terminate a Python script or a program to avoid the execution of the program till infinite time. One easy method is to use the return statement. The return statement terminates the script and returns a value.
It is essential to terminate a script correctly. In some cases, you may need to stop a script abruptly, while in other cases, you need to execute some cleanup code before terminating the script. In this article, we will learn some of the most common methods of terminating a Python script.
1. Use Keyboard Shortcut to Terminate a Script
This is the most common method to terminate the execution of a script in Python. Let’s say you have started the execution of the program and you feel the need to stop the execution of the script just Press the Ctrl + C Keys.
# Key commands to terminate script
# In windows
Ctrl + C
On the Windows operating system, to terminate the execution of a Python script press the Ctrl + C. However, if you are on Linux the shortcut for the termination of the script is Ctrl + Z.
# Key commands to terminate script
# In Linux
Ctrl + Z
2. sys.exit() – Terminate a Script
The sys.exit() function allows you to terminate a Python script programatically. When the sys.exit() function is called, it raises the SystemExit exception with an optional exit status code.
The exit status code can be used to indicate the reason for termination, and it is usually zero to indicate successful termination and non-zero to indicate an error. We can also pass a custom message inside the function.
# Using sys.exit() function to exit the script
import sys
# Your code here
if some_condition:
# Exit with error code 1
sys.exit(1)
As mentioned above we can also exit the execution with a custom message that is passed to the function. See the following example:
# Using sys.exit() with custom message
import sys
while True:
print(‘Working’)
sys.exit(‘Terminated The Execution’)
# Output:
# Working
# Terminated The Execution
The sys.exit() as mentioned earlier raises the SystemExit exception. And we can use it like the one below with try-except statement.
# Using sys.exit() with try-catch
import sys
try:
# some code here
sys.exit(‘worked’) # exit with status code 0
except SystemExit:
print(“Program exited.”)
3. exit() – Stop Execution of Python Script
The exit() function in Python is a built-in function, you can use it to immediately terminate a script with an optional exit status code. Unlike other functions, exit() does not raise any exceptions. Instead, it terminates the script immediately without executing any further code.
The exit() function takes a single optional argument, which is the exit status code. If no argument is provided, the exit status code defaults to 0, which indicates the successful termination of the script.
# Using exit()
if True:
exit(1)
4. quit() – Terminate the Execution of Python Program
When quit() is called, the Python interpreter will terminate immediately without executing any further code. Unlike exit(), quit() is not intended to be used in scripts or programs, but rather in interactive mode or in the Python shell. Though the quit() function also works in the script mode, however, it is recommended by the documentation to use it in the interactive mode.
# Using quit() function on terminal
>>> print(“Hello, World!”)
Hello, World!
>>> quit()
5. Using the KeyboardInterrupt Exception
The KeyboardInterrupt exception in Python is a built-in exception that is raised when the user interrupts the execution of a program or script using the keyboard, typically by pressing Ctrl+C in the terminal or command prompt.
When a KeyboardInterrupt exception is raised, the program or script will terminate immediately without executing any further code. However, you can use a try–except block to catch the exception and perform any necessary cleanup tasks before exiting.
# Using the KeyboardInterrupt Exception
import time
try:
while True:
print(“Program is running…”)
time.sleep(1)
except KeyboardInterrupt:
print(“User interrupted the program.”)
# Perform any necessary cleanup tasks
6. os._exit() – Terminate Python Script
The os._exit() function in Python is a way to immediately terminate a program or script without performing any cleanup or running any finally blocks. Unlike exit() and sys.exit(), os._exit() does not raise any exceptions or perform any cleanup tasks. Instead, it immediately terminates the program with a specified exit code.
# Using os._exit() to terminate script
import os
os._exit(0)
os._exit() should be used with caution, as it can leave files open, connections established, and other resources in an inconsistent state.
7. Raise SystemExit Exception
The SystemExit exception in Python is a built-in exception that is raised when the exit() function is called, or when the user interrupts the program using Ctrl+C (which raises a KeyboardInterrupt exception that is caught and re-raised as a SystemExit exception).
# Raise SystemExit Exception to Terminate
try:
# Perform some tasks
raise SystemExit(0)
except:
# Handle any exceptions that occur
print(‘Execution teminated’)
8. Summary and Conclusion
In this article, We have discussed how to terminate the execution of the Python script or a program in several ways. Now you can choose the methods that are best fit for you. I hope this article was helpful. Let me know if you have a question.
Happy Coding!
It is necessary to terminate a Python script or a program to avoid the execution of the program till infinite time. One easy method is to use the return statement. The return statement terminates the script and returns a value. It is essential to terminate a script correctly. In some cases, you may need to Read More Python, Python Tutorial