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