9/2/26About 1 minAbout 185 words
Concept: Exit code
When a script is executed, it will return an exit code to the operating system when it finishes running. The exit code is a number that indicates whether the script ran successfully or encountered an error.
The exit code is typically 0 for a successful execution, and a non-zero value for an error.
In order to exit a script with a specific exit code, the exit function from the sys module must be used.
import sys
import random
if random.randint(0,1) == 0:
print("Script ran successfully.")
sys.exit(0)
else:
print("Script encountered an error.")
sys.exit(1)An error code must be a positive integer no larger than 255. There are a few reserved exit code which should not be used outside their intended purpose. Any other code can be used to indicate an application specific error.
| Exit code | Meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse of shell builtins |
| 126 | Command invoked cannot execute |
| 127 | Command not found |
| 128 | Invalid argument to exit |
| 130 | Script terminated by Control-C |