【发布时间】:2019-06-19 18:36:27
【问题描述】:
我有一组布尔 argparse 选项:--foo/--no-foo、--bar/--no-bar、--baz/--no-baz
仅当这些选项中的至少一个设置为 True 时,我的脚本才有意义。
我想发出一个由argparse 正确处理的异常,它将作为命令行错误清除消息进行管理。
但是argparse.ArgumentTypeError 不是一个好的选择,因为它需要该选项作为构造函数的第一个参数……而我的情况与多个选项有关。
[根据@00 评论编辑:] 我现在唯一的解决方案是在命令行处理结束时提出 ValueError 是没有设置这些选项。但它是一个例外,对用户不友好。
遇到这种情况怎么办?
非常感谢。
P.S.:生成这些选项的代码:
@classmethod
def addBoolean(
cls, argumentParser, dest, helpTrue, helpFalse,
default=None
):
"""Adds a boolean option
- argumentParser: A argparse.ArgumentHelper object
- dest: The destination argument
- helpTrue: The documentation of the True option
- helpFalse: The documentation of the False option
- default: Value to use if not required and not provided
When no default (None) is provided, required is True
The option will be --{dest} and --no-{dest}
"""
# pylint: disable=too-many-arguments
required = (default is None)
group = argumentParser.add_mutually_exclusive_group(
required=required,
)
group.add_argument(
f'--{dest}',
dest=dest,
action='store_true',
help=helpTrue
)
group.add_argument(
f'--no-{dest}',
dest=dest,
action='store_false',
help=helpFalse
)
if not required:
argumentParser.set_defaults(**{dest: default})
【问题讨论】:
-
您总是可以在初始解析之后抛出异常/错误消息,也就是说,在 argparse 之外自己编写检查代码。也许不太好,但我会说它会很好用。
-
@00 确实,这就是我现在所做的。我已经相应地编辑了问题。
-
查看这个答案:stackoverflow.com/a/6723066/6018688 在自定义检查过去解析后使用
parser.error。 -
谢谢@fabianegli。我没见过这个。
-
@MichaelHooreman 不客气。希望它有所帮助:-)
标签: python python-3.x argparse