【问题标题】:Why does Python's argparse use an error code of 2 for SystemExit?为什么 Python 的 argparse 对 SystemExit 使用错误代码 2?
【发布时间】:2014-05-17 18:06:40
【问题描述】:

当我给出它不喜欢的 Python 的 argparse 输入时,它会引发一个代码为 2 的 SystemExit,即seems to mean "No such file or directory"。为什么要使用这个错误码?

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

产生这个输出:

usage: se.py [-h] arg
se.py: error: too few arguments
Got error code 2 which is ENOENT in errno

【问题讨论】:

  • 退出码对于不同的系统有不同的含义。 errno 代码是一个完全不同的标准。
  • @MartijnPieters,我没有意识到这一点。是否有任何关于 argparse 正在使用的标准(如果有)的信息?
  • @frostnational:那是关于 errno 错误代码,不是关于为什么 argparse 使用 2 作为退出代码。你和这里的 OP 犯了同样的错误。

标签: python argparse errno


【解决方案1】:

您将C errno error codes 与进程exit status 混淆了;这两个概念完全不相关。

退出状态值have no official standard,但按照约定 2 表示使用不正确;例如,这是exit code used by Bash built-ins

os module 公开了代表许多 POSIX 系统使用的 sysexit.h 常量的 os.EX_* 常量。 os.EX_USAGE 是退出代码 64,也可以使用,尽管 argparse 实际上并没有使用这个常量,因为它只在 UNIX 系统上可用,而 argparse 也需要在 Windows 和其他平台上工作。

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 2018-08-31
    • 2014-05-24
    • 2013-06-06
    • 2022-06-22
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多