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)
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 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.