Why does Python's argparse use an error code of 2 for SystemExit?

最后都变了- 提交于 2019-12-24 11:15:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!