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

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

问题描述

当我不喜欢Python的argparse输入时,它将引发代码为2的SystemExit,其中<​​a href ="https://docs.python.org/2/library/errno.html"相对="nofollow">似乎表示没有此类文件或目录" .为什么使用此错误代码?

  import argparse进口errno解析器= argparse.ArgumentParser()parser.add_argument('arg')尝试:parser.parse_args([])除了SystemExit本身:print(错误代码{}在errno中为{}".format(se.code,errno.errorcode [se.code])) 

产生以下输出:

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

解决方案

您正在混淆 C errno 错误代码(进程为退出状态;这两个概念是完全不相关的.

退出状态值没有官方标准,但习惯上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天全站免登陆