问题描述
我试图在不同组之间建立一个互斥组:我有参数 -a、-b、-c,我想与 -a 和 -b 一起发生冲突,或者 -a 和 -c 一起发生冲突.帮助应该显示类似 [-a |([-b] [-c])].
I'm trying to have a mutually exclusive group between different groups:I have the arguments -a,-b,-c, and I want to have a conflict with -a and -b together, or -a and -c together. The help should show something like [-a | ([-b] [-c])].
以下代码似乎没有互斥选项:
The following code does not seem to do have mutually exclusive options:
import argparse
parser = argparse.ArgumentParser(description='My desc')
main_group = parser.add_mutually_exclusive_group()
mysub_group = main_group.add_argument_group()
main_group.add_argument("-a", dest='a', action='store_true', default=False, help='a help')
mysub_group.add_argument("-b", dest='b', action='store_true',default=False,help='b help')
mysub_group.add_argument("-c", dest='c', action='store_true',default=False,help='c help')
parser.parse_args()
解析不同的组合——全部通过:
Parsing different combinations - all pass:
> python myscript.py -h
usage: myscript.py [-h] [-a] [-b] [-c]
My desc
optional arguments:
-h, --help show this help message and exit
-a a help
> python myscript.py -a -c
> python myscript.py -a -b
> python myscript.py -b -c
我尝试将 mysub_group
更改为 add_mutually_exclusive_group
将所有内容都变成互斥的:
I tried changing the mysub_group
to be add_mutually_exclusive_group
turns everything into mutually exclusive:
> python myscript.py -h
usage: myscript.py [-h] [-a | -b | -c]
My desc
optional arguments:
-h, --help show this help message and exit
-a a help
-b b help
-c c help
如何为 [-a | 添加参数([-b] [-c])]?
How can I add arguments for [-a | ([-b] [-c])]?
推荐答案
所以,这个问题已经被问过很多次了.简单的答案是使用 argparse,你不能".然而,这就是简单的答案.您可以使用子解析器,因此:
So, this has been asked a number of times. The simple answer is "with argparse, you can't". However, that's the simple answer. You could make use of subparsers, so:
import argparse
parser = argparse.ArgumentParser(description='My desc')
sub_parsers = parser.add_subparsers()
parser_a = sub_parsers.add_parser("a", help='a help')
parser_b = sub_parsers.add_parser("b", help='b help')
parser_b.add_argument("-c", dest='c', action='store_true',default=False,help='c help')
parser.parse_args()
然后你得到:
$ python parser -h
usage: parser [-h] {a,b} ...
My desc
positional arguments:
{a,b}
a a help
b b help
optional arguments:
-h, --help show this help message and exit
和:
$ python parser b -h
usage: parser b [-h] [-c]
optional arguments:
-h, --help show this help message and exit
-c c help
如果您更喜欢问题中所述的论点,请查看 docopt,它看起来像可爱,应该做你想做的.
If you would prefer your arguments as stated in the question, have a look at docopt, it looks lovely, and should do exactly what you want.
这篇关于组间使用互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!