Python 3.9.1 argparse exit_on_error 在某些情况下不工作

Python 3.9.1 argparse exit_on_error not working in certain situations

我正在编写一个包含元命令的 REPL。元命令可以采用选项和参数,我正在尝试使用 argparse 来处理它们。因此,如果用户没有正确使用命令,我不想完全退出程序。最多,我想打印一条使用信息并继续 REPL。这是我正在尝试的基本想法:

import argparse

p = argparse.ArgumentParser(exit_on_error=False)

p.add_argument('foo')

try:
    p.parse_args([])   # I want to catch the case of a user not supplying a required positional arg
except argparse.ArgumentError:
    print("error detected")

然而,运行 上面的片段给了我这个(并在之后立即退出):

usage: test.py [-h] foo
test.py: error: the following arguments are required: foo

Python 3.9 文档是这样说的:

Normally, when you pass an invalid argument list to the parse_args() method of an ArgumentParser, it will exit with error info.

If the user would like to catch errors manually, the feature can be enabled by setting exit_on_error to False:

可能是我误解了“无效参数列表”的含义(文档中给出的示例确实有效),但我认为空参数列表适用于这种情况。

我知道还有其他方法可以处理这个问题(我已经成功测试了其中的一两个),但我只是想确保我没有遗漏 exit_on_error 参数.也就是说,有人知道为什么这不起作用吗?

该参数仅处理一类错误,即处理特定参数时引发的错误。所需参数的测试处理方式不同,不会被此参数转移。我怀疑这个问题已经在 Python bug/issues 上提出,但我并没有太在意它。更改 parser.error 或 parser.exit 方法适用于两类错误。