mutually_exclusive_group 带有可选和位置参数

mutually_exclusive_group with optional and positional argument

我用 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

首先,您应该包括 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'])