【问题标题】:How to forbid two conflicting options如何禁止两个冲突的选项
【发布时间】:2021-07-14 01:15:24
【问题描述】:

有没有办法向 Python 的 ArgumentParser 指定两个可选标志冲突?

arg_parser.add_argument('-c', '--clean', action='store_true')
arg_parser.add_argument('-d', '--dirty', action='store_true')

我希望用户能够不指定这些,或者只指定一个。

没有其他条件可以实现吗?

【问题讨论】:

    标签: python command-line-arguments argparse


    【解决方案1】:

    添加mutually exclusive group怎么样:

    group = arg_parser.add_mutually_exclusive_group()
    group.add_argument('-c', '--clean', action='store_true')
    group.add_argument('-d', '--dirty', action='store_true')
    

    这样我得到以下行为:

    >>> arg_parser.parse_args(['--clean']) 
    Namespace(clean=True, dirty=False)
    >>> arg_parser.parse_args(['--dirty']) 
    Namespace(clean=False, dirty=True)
    >>> arg_parser.parse_args(['--dirty','--clean']) 
    usage: PROG [-h] [-c | -d] PROG: error: argument -c/--clean: not allowed with argument -d/--dirty
    

    【讨论】:

    • 我尝试了相同的方法,但是对于定义为获取值的参数,但它不起作用: group.add_argument("-v", "--verbose", type=str, nargs='?') group.add_argument("-q", "--quiet", type=str, nargs='?') 知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-06-21
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多