When you run a Python script from the command line, a shell script, or another program, you need to tell the caller whether the process finished successfully or ended with an error. This is done using the “Exit Status (Exit Code).”
Normally, when a Python program reaches the end, the exit status automatically becomes 0 (Success). However, there are times when you want to intentionally return a non-zero value (Error) to terminate the program, such as when an error occurs. The sys.exit() function is used for this purpose.
This article explains how to use sys.exit() and how to utilize exit statuses.
Basic Rules of Exit Status
In the programming world (especially in Unix/Linux systems), there is a convention to represent the termination state of a process with the following integers:
0: Normal Termination (Success). Indicates that the process completed without errors.1or greater: Abnormal Termination (Error). Indicates that some problem occurred (usually1is used).
Basic Usage of sys.exit()
To use sys.exit(), you need to import the standard library sys module. By passing an integer as an argument, you can immediately terminate the program with that number as the exit status.
Specific Code Example
As an example, let’s create a program that checks the integrity of input data and exits with error code 1 if it is invalid.
import sys
def main_process(user_id):
print(f"Start processing: Checking User ID {user_id}.")
# Rule: User ID must be a positive integer
if user_id <= 0:
# Output error message to standard error (Recommended)
print("Error: User ID must be an integer of 1 or greater.", file=sys.stderr)
# Stop the program with exit status 1 (Abnormal termination)
sys.exit(1)
print("Check complete: Data is valid.")
print("Executing main process...")
# ... Some processing ...
print("Process complete.")
# You can also explicitly exit with 0 (Defaults to 0 if omitted)
sys.exit(0)
# --- Execution ---
# Case 1: Passing invalid data
main_process(-5)
Output:
Start processing: Checking User ID -5.
Error: User ID must be an integer of 1 or greater.
The program stops there, and “Executing main process…” is not displayed.
How to Check Exit Status
You can check the set exit status in the “shell (terminal)” where you executed the Python script.
Linux / macOS (bash, zsh)
The exit status of the immediately preceding command is stored in the special variable $?.
$python script.py$ echo $?
1
Windows (Command Prompt)
The exit status of the immediately preceding command is stored in the environment variable %ERRORLEVEL%.
> python script.py
> echo %ERRORLEVEL%
1
By using this mechanism, you can control flow in shell scripts, such as “If the Python script succeeds, proceed to the next step; if it fails, abort.”
Passing a Message to sys.exit()
You can also pass a string instead of an integer to the argument of sys.exit(). If you pass a string, the following actions occur:
- The string is printed to Standard Error (stderr).
- The program exits with an exit status of
1.
This allows you to write the error message display and termination in a single line.
import sys
filename = "config.ini"
# Assume the file type is incorrect
if filename != "config.json":
# Display message and exit with status 1
sys.exit(f"Fatal Error: Format of config file '{filename}' is invalid.")
Output:
Fatal Error: Format of config file 'config.ini' is invalid.
Summary
- Use
sys.exit()to terminate a Python script with an arbitrary status. sys.exit(0)means normal termination, andsys.exit(1)means abnormal termination.sys.exit("Message")displays the error message and exits with status1.- This feature is very important when automating tasks in coordination with other programs or shell scripts.
