Python sys.exit() method
The Python sys.exit() method is used to terminate the execution of a program. It optionally accepts an integer or a string as an argument which is used as the exit status. By convention an argument of zero indicates successful termination while any non-zero value indicates an error.
If sys.exit() method is called with a string then the string is printed to 'stderr' before exiting. Internally it raises a SystemExit exception which can be caught to prevent the program from exiting. This method is commonly used to exit a script early due to errors or specific conditions.
Syntax
Following is the syntax and parameters of Python sys.exit() method −
sys.exit([arg])
Parameters
This method accepts a single optional parameter arg representing the exit status.
Return value
This method does not return any value.
Example 1
Following is the example of sys.exit() method which clears the cache after compiling and using some regular expressions −
import sys
print("This message will be printed.")
sys.exit(0)
print("This message will not be printed.")
Output
This message will be printed.
Example 2
This example exits the program with status 1 indicating an error. The second print statement will not be executed −
import sys
print("An error occurred.")
sys.exit(1)
print("This message will not be printed.") # This line will not be executed.
Output
An error occurred.
Example 3
Here in this example we check for command-line arguments. If no arguments are provided it exits the program with a message. The message will be printed to stderr −
import sys
if len(sys.argv) < 2:
sys.exit("No arguments provided. Exiting the program.")
print("Arguments provided. Continuing the program.")
Output
No arguments provided. Exiting the program.
Example 4
This example prompts the user to enter a positive number. If a negative number is entered it raises a ValueError and exits the program with an error message −
import sys
try:
x = int(input("Enter a positive number: "))
if x < 0:
raise ValueError("Negative number entered.")
except ValueError as e:
sys.exit(f"Error: {e}")
print("You entered a positive number.")
Output
Enter a positive number: -1 Error: Negative number entered.
python_modules.htm