mutual_exclusive_group,带有可选和位置参数

时间:2016-04-25 05:50:00

标签: python argparse docopt

我创建了一个带有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

1 个答案:

答案 0 :(得分:6)

首先,您应该包含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'])
相关问题