Skip to main content
 首页 » 编程设计

python之为什么 Python 的 argparse 对 SystemExit 使用错误代码 2

2025年05月04日11pander-it

当我给 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 

请您参考如下方法:

你在混淆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 上工作,并且其他平台也是如此。