为什么 Python 的 argparse 对 SystemExit 使用错误代码 2? [英] Why does Python's argparse use an error code of 2 for SystemExit?

查看:57
本文介绍了为什么 Python 的 argparse 对 SystemExit 使用错误代码 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我提供 Python 不喜欢的 argparse 输入时,它会引发一个 SystemExit,代码为 2,其中 似乎意味着没有这样的文件或目录".为什么要使用这个错误代码?

导入 argparse导入错误号解析器 = argparse.ArgumentParser()parser.add_argument('arg')尝试:parser.parse_args([])除了 SystemExit 如下:打印(得到错误代码{},这是在errno中的{}".format(se.code, errno.errorcode[se.code]))

产生这个输出:

用法:se.py [-h] argse.py:错误:参数太少得到错误代码 2,它是 errno 中的 ENOENT

解决方案

你很困惑 C errno error 代码 带有进程退出状态;这两个概念完全不相关.

退出状态值没有官方标准, 但按照惯例 2 表示不正确的用法;例如,这是Bash 内置程序使用的退出代码.>

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

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

解决方案

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.

这篇关于为什么 Python 的 argparse 对 SystemExit 使用错误代码 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆