python - 具有可选和位置参数的 mutually_exclusive_group

标签 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

最佳答案

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

关于python - 具有可选和位置参数的 mutually_exclusive_group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36832893/

相关文章:

Python argparse.ArgumentParser 无法区分 `--modes` 和 `--mode`

python - 类型错误 : __call__() missing 1 required positional argument: 'send' Django

python - 如何使用我在 python 中创建的简单模块?

python - argparse:如何配置多选、多值、可选参数?

python - python3 参数定义中的 docopt

python - 如何在 Python 的 argparse 模块中收集两个选项,每个选项都有多个参数?

python - 为什么我的 docopt 选项没有默认值?

python - Tk/ttk python 中的帧大小调整问题

Python 类方法 - 有没有办法缩短调用时间?

argparse 的 python 单元测试