python - 在 Python 中使用 'argparse.ArgumentError'

标签 python argparse

我想在 Python 的 argparse 模块中使用 ArgumentError 异常,但我不知道如何使用它。签名说它应该被称为 ArgumentError(argument, message),但我不知道 argument 应该是什么。我认为它应该是解析器对象的一部分,但我找不到任何文档。

最佳答案

来自 the source documentation :

ArgumentError: The exception raised by ArgumentParser objects when there are errors with the parser's actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.

构造函数的argument 参数是引发异常的Action 对象。通常不需要在 Action 子类之外引发它,在子类化时也不需要显式引发它;您通常会提出 ValueError (或任何合适的)。

0 到 1 之间的浮点值

关于您的评论,您只想接受 0 到 1 之间的浮点值。为此,您应该使用定义自定义类型的能力。例如,您可以这样做:

def percentFloat (string):
    value = float(string)
    if value < 0 or value > 1:
        raise argparse.ArgumentTypeError('Value has to be between 0 and 1')
    return value

parser = argparse.ArgumentParser()
parser.add_argument('test', type=percentFloat)
parser.parse_args()

请注意,这对于非 float 也是安全的,因为 float(string) 将为非 float 引发 ValueError,这也会触发由 argparse 模块。 ArgumentTypeError只是一种指定自定义错误消息的方法。

互斥参数

对于互斥参数,你应该使用argparse.add_mutually_exclusive_group .

参数依赖

参数依赖并不是真正应该由参数解析器来完成的事情。对于语义细节,您应该自己做:

args = parser.parse_args()
if args.w and not args.p:
    parser.error('-p is required when -w is set.')

您可以使用 ArgumentParser.error引发自定义错误消息,这将中断程序并打印到控制台。

当然,在这种基本情况下,如果可能的话,隐式猜测 -p 会更有意义。

关于python - 在 Python 中使用 'argparse.ArgumentError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8107713/

相关文章:

python - argparse 可以用来初始化字符串的默认值吗

python - 如何从 ArgumentParser 获取参数列表

python - 如何使用 argparse 正确调用函数?

python - 多处理池中的全局变量

php - 让 PHP 运行 Python 脚本

python - 检查字符串在多列中的存在,并将输出输出到 pandas 中的单独列

python - 如何阻止在py2exe中编译的Python程序显示ImportError : No Module names 'ctypes'

python - 是否有一个 numpy 函数返回给定大小的数组索引矩阵?

python - 使用 pip install -e 在 setup.py 中安装 data_files

Python:如何使用argparse在子解析器中具有互斥组?