带有可选和位置参数的互斥组 [英] mutually_exclusive_group with optional and positional argument
问题描述
我使用 docopt 创建了一个 cli 规范,效果很好,但是由于某种原因我不得不重写它到 argparse
I created an cli specification with docopt which works great, however for some reason I have to rewrite it to argparse
Usage:
update_store_products <store_name>...
update_store_products --all
Options:
-a --all Updates all stores configured in config
怎么做?
重要的是我不想拥有这样的东西:
What is important I don't want to have something like this:
update_store_products [--all] <store_name>...
我认为应该是这样的:
update_store_products (--all | <store_name>...)
我尝试使用 add_mutually_exclusive_group,但我有错误:
I tried to use add_mutually_exclusive_group, but I got error:
ValueError: mutually exclusive arguments must be optional
推荐答案
首先,您应该包含重现问题所需的最短代码问题本身的错误.没有它,答案只是在黑暗中的一个镜头.
First off, you should include the shortest code necessary to reproduce the error in the question itself. Without it an answer is just a shot in the dark.
现在,我愿意打赌你的 argparse
定义看起来有点像这样:
Now, I'm willing to bet your argparse
definitions look a bit something like this:
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--all', action='store_true')
group.add_argument('store_name', nargs='*')
互斥组中的参数必须是可选的,因为在那里有一个必需的参数没有多大意义,因为该组只能有那个参数.仅 nargs='*'
是不够的 - 创建的 action 将是 True
- 说服互斥组该参数是真正可选的.您需要做的是添加一个默认值:
The arguments in a mutually exclusive group must be optional, because it would not make much sense to have a required argument there, as the group could then only have that argument ever. The nargs='*'
alone is not enough – the required
attribute of the created action will be True
– to convince the mutex group that the argument is truly optional. What you have to do is add a default:
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'])
这篇关于带有可选和位置参数的互斥组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!