【问题标题】:mutually_exclusive_group with optional and positional argument具有可选和位置参数的互斥组
【发布时间】:2016-04-25 17:03:34
【问题描述】:

我使用 docopt 创建了一个 cli 规范,效果很好,但是由于某种原因我必须将其重写为 argparse

Usage:
    update_store_products <store_name>...
    update_store_products --all

    Options:
      -a --all     Updates all stores configured in config

怎么做?

重要的是我不想拥有这样的东西:

update_store_products [--all] <store_name>...

我认为应该是这样的:

update_store_products (--all | <store_name>...)

我尝试使用add_mutually_exclusive_group,但出现错误:

ValueError: mutually exclusive arguments must be optional

【问题讨论】:

    标签: python argparse docopt


    【解决方案1】:

    首先,您应该包含the shortest code necessary to reproduce the error in the question itself。没有它,答案只是在黑暗中开枪。

    现在,我敢打赌你的 argparse 定义看起来有点像这样:

    parser = ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--all', action='store_true')
    group.add_argument('store_name', nargs='*')
    

    互斥组中的参数必须是可选的,因为在那里有一个必需的参数没有多大意义,因为该组只能有那个参数。仅nargs='*' 是不够的——创建的actionrequired 属性将是True——说服互斥组该参数是真正可选的。你要做的就是添加一个默认值:

    parser = ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--all', action='store_true')
    group.add_argument('store_name', nargs='*', default=[])
    

    这将导致:

    [~]% python2 arg.py
    usage: arg.py [-h] (--all | store_name [store_name ...])
    arg.py: error: one of the arguments --all store_name is required
    
    [~]% python2 arg.py --all
    Namespace(all=True, store_name=[])
    
    [~]% python2 arg.py store1 store2 store3
    Namespace(all=False, store_name=['store1', 'store2', 'store3'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 2019-09-22
      • 2016-05-04
      • 2017-01-03
      • 2014-01-18
      • 2015-04-20
      • 2020-07-14
      • 2013-03-09
      相关资源
      最近更新 更多