问题
When I give Python's argparse input it doesn't like, it raises a SystemExit with a code of 2, which seems to mean "No such file or directory". Why use this error code?
import argparse
import errno
parser = argparse.ArgumentParser()
parser.add_argument('arg')
try:
parser.parse_args([])
except SystemExit as se:
print("Got error code {} which is {} in errno"
.format(se.code, errno.errorcode[se.code]))
produces this output:
usage: se.py [-h] arg
se.py: error: too few arguments
Got error code 2 which is ENOENT in errno
回答1:
You are confusing C errno error codes with a process exit status; the two concepts are entirely unrelated.
Exit status values have no official standard, but by convention 2 is taken to mean Incorrect usage; this is the exit code used by Bash built-ins, for example.
The os module exposes os.EX_*
constants that represent the sysexit.h
constants used by many POSIX systems. os.EX_USAGE is exit code 64 and could be used as well, although argparse
doesn't actually use this constant as it is only available on UNIX systems while argparse
needs to work on Windows and other platforms too.
来源:https://stackoverflow.com/questions/23714542/why-does-pythons-argparse-use-an-error-code-of-2-for-systemexit