Are there any established exit code standards or reserved exit codes in Python (specifically, Python CLI utilities)? (e.g., /usr/include/sysexits.h for C in UNIX platforms, or http://tldp.org/LDP/abs/html/exitcodes.html for Bash scripts)
The function calls exit(0) and exit(1) are used to reveal the status of the termination of a Python program. The call exit(0) indicates successful execution of a program whereas exit(1) indicates some issue/error occurred while executing a program.
exit(0) means a clean exit without any errors / problems. exit(1) means there was some issue / error / problem and that is why the program is exiting. This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was.
255: Exit code out of range.
The os
module provides several exit code constants you can use.
sys.exit(os.EX_OK)
sys.exit(os.EX_USAGE)
Regarding Portability
While exit codes can be useful, they may introduce portability problems. The documentation warns:
Note: Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
So if you want to use exit codes, and your code needs to be portable, you'll have to do a bit more error checking. The sys.exit()
docs suggest using a string error message or the integer 1 on failure.
import os
import sys
try:
subcommand = sys.argv[1]
except IndexError:
try:
sys.exit(os.EX_USAGE)
except AttributeError:
sys.exit("missing argument: subcommand")
For successful exits:
import os
import sys
subcommand = sys.argv[1]
if subcommand == 'noop':
try:
sys.exit(os.EX_OK)
except:
sys.exit()
print(subcommand)
Given the extra complexity exit codes introduce, you may be better off skipping them if you don't actually need them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With