Of course! In Python, the concept of an "errorlevel" (common in shell scripting like bash or cmd) is handled differently. Python scripts don't have a built-in global "errorlevel" variable that you check after each command.

Instead, Python uses exceptions to signal errors and the sys.exit() function to set an exit code for the script.
Here’s a complete breakdown of how to handle this in Python.
The Core Concept: sys.exit() and Exit Codes
When you run a Python script from your terminal, it exits with an "exit code" (also known as a "return code" or "status code").
sys.exit(0): Indicates successful completion. This is the default if the script finishes without any unhandled exceptions.sys.exit(1): A common convention to indicate a general error or that the script did not complete successfully.- Any other integer: You can use any non-zero integer to represent specific types of failures. For example,
sys.exit(2)could mean "invalid arguments" andsys.exit(3)could mean "file not found".
How to use it:

- Import the
sysmodule. - Call
sys.exit(code)at any point in your script.
Example 1: Successful Exit
# success.py
print("Starting the script...")
print("Everything went well.")
# No sys.exit() call means the script exits with code 0 (success)
Running it:
$ python success.py Starting the script... Everything went well. $ echo $? 0
is a shell variable that holds the exit code of the last command.
Example 2: Failure Exit
# failure.py
import sys
print("Starting the script...")
print("Something went wrong!")
# Explicitly exit with an error code
sys.exit(1)
Running it:
$ python failure.py Starting the script... Something went wrong! $ echo $? 1
Handling Errors with try...except
A key feature of Python is its exception handling. You can anticipate that a part of your code might fail (e.g., trying to open a file that doesn't exist) and handle it gracefully.
You can combine try...except blocks with sys.exit() to create robust error handling.
Example 3: Handling a Specific Error
Let's say a script needs a configuration file. If the file isn't found, it should exit with a specific error code.
# config_reader.py
import sys
config_file_path = "my_config.txt"
try:
print(f"Attempting to open {config_file_path}...")
with open(config_file_path, 'r') as f:
content = f.read()
print("File content:")
print(content)
except FileNotFoundError:
print(f"Error: The configuration file '{config_file_path}' was not found.")
sys.exit(2) # Exit with code 2 to indicate "file not found"
except Exception as e:
print(f"An unexpected error occurred: {e}")
sys.exit(1) # Exit with a general error code
print("Script finished successfully.")
# The script will only reach here if no exceptions were raised.
Running it when the file exists:
$ echo "some data" > my_config.txt $ python config_reader.py Attempting to open my_config.txt... File content: some data Script finished successfully. $ echo $? 0
Running it when the file does NOT exist:
$ rm my_config.txt $ python config_reader.py Attempting to open my_config.txt... Error: The configuration file 'my_config.txt' was not found. $ echo $? 2
The "Pythonic" Way: try...except...finally
For more complex scenarios, you can use a finally block. The code inside finally will always run, whether an exception occurred or not. This is perfect for cleanup actions like closing database connections or releasing resources.
# resource_manager.py
import sys
file_handle = None
try:
print("Opening resource...")
file_handle = open("data.txt", 'r')
# Simulate an error
result = 10 / 0
except FileNotFoundError:
print("Error: data.txt not found.")
sys.exit(3)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
sys.exit(4)
finally:
# This block runs no matter what
if file_handle:
print("Closing the file handle in the 'finally' block.")
file_handle.close()
print("This line will not be reached.")
Running it:
$ python resource_manager.py Opening resource... Error: Cannot divide by zero. Closing the file handle in the 'finally' block. $ echo $? 4
Notice that the file was closed even though an error occurred, which is the desired behavior.
Best Practices
-
Use Meaningful Exit Codes: While
1is a general error, using other numbers can help calling scripts diagnose the problem. A common convention is:0: Success1: General/catch-all error2: Misuse of shell commands (e.g., wrong number of arguments)126: Command invoked cannot be executed127: Command not found>= 128: Fatal error signal (e.g.,128 + SIGSEGV)
-
Let the Main Logic Control the Exit: Don't sprinkle
sys.exit()everywhere. It's cleaner to structure your code so that the main part of your script returns a value, and a singlesys.exit()call at the end handles the exit code.# main_function_pattern.py import sys def process_data(): # Some complex logic if some_condition_is_bad: return "error_code_5" # Or return 5 return "success" result = process_data() if result == "success": print("Processing complete.") sys.exit(0) else: print(f"Processing failed with code: {result}") sys.exit(result) # Assuming result is an integer here -
Use
sys.exit()for Script-Level Exits: For library code that might be imported by other scripts, it's often better to raise an exception instead of callingsys.exit(). This allows the calling script to decide how to handle the error.sys.exit()should be used at the top level of your script.
Summary: Shell errorlevel vs. Python
| Feature | Shell (Bash/Cmd) | Python |
|---|---|---|
| Mechanism | Global variable (Bash) or %ERRORLEVEL% (Cmd) is set after a command finishes. |
sys.exit(code) is called explicitly in your script. |
| Error Signaling | Commands return non-zero exit codes on failure. | Exceptions are raised to signal an error condition. |
| Error Handling | if statements check the exit code of the previous command. |
try...except blocks catch and handle exceptions. |
| Success Code | 0 |
0 (default) |
| Failure Code | Any non-zero integer (1, 2, 127, etc.) |
Any non-zero integer (1, 2, 5, etc.) |
