具有可选参数和位置参数的common_exclusive_group [英] mutually_exclusive_group with optional and positional argument

查看:50
本文介绍了具有可选参数和位置参数的common_exclusive_group的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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='*'是不够的–创建的required属性> 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'])

这篇关于具有可选参数和位置参数的common_exclusive_group的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆