noi*_*isy 2 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
Run Code Online (Sandbox Code Playgroud)
怎么做?
什么是重要的我不想有这样的东西:
update_store_products [--all] <store_name>...
Run Code Online (Sandbox Code Playgroud)
我认为这将是这样的:
update_store_products (--all | <store_name>...)
Run Code Online (Sandbox Code Playgroud)
我尝试使用add_mutually_exclusive_group,但是我收到了错误:
ValueError: mutually exclusive arguments must be optional
Run Code Online (Sandbox Code Playgroud)
首先,您应该包含在问题本身中重现错误所需的最短代码.没有它,答案只是在黑暗中拍摄.
现在,我愿意打赌你的argparse定义看起来像这样:
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--all', action='store_true')
group.add_argument('store_name', nargs='*')
Run Code Online (Sandbox Code Playgroud)
互斥组中的参数必须是可选的,因为在那里有一个必需的参数没有多大意义,因为该组只能拥有该参数.该nargs='*'是不够的-在required创建的属性作用将是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=[])
Run Code Online (Sandbox Code Playgroud)
这将导致:
[~]% 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'])
Run Code Online (Sandbox Code Playgroud)