Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit Code Standards in Python

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)

like image 404
Ruslan Nabioullin Avatar asked Jun 20 '11 15:06

Ruslan Nabioullin


People also ask

What are exit codes in Python?

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.

What is exit 0 and exit 1 Python?

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.

What is exit code 255 Python?

255: Exit code out of range.


1 Answers

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.

like image 190
Brad Koch Avatar answered Sep 26 '22 01:09

Brad Koch