Exit Code Standards in Python

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.


Provided you are on a POSIX platform, you can access the constants from sysexit.h via the os module:

>>> import os
>>> os.EX_ <tab pressed>
os.EX_CANTCREAT    os.EX_NOHOST       os.EX_OK           os.EX_SOFTWARE
os.EX_CONFIG       os.EX_NOINPUT      os.EX_OSERR        os.EX_TEMPFAIL
os.EX_DATAERR      os.EX_NOPERM       os.EX_OSFILE       os.EX_UNAVAILABLE
os.EX_IOERR        os.EX_NOUSER       os.EX_PROTOCOL     os.EX_USAGE

See the documentation for sys.exit().

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.