在组之间使用互斥 [英] Using mutually exclusive between groups
问题描述
我正在尝试在不同的组之间建立一个互斥的组: 我有-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.
这篇关于在组之间使用互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!