python argparse:使用两组必需的参数 [英] python argparse : use two groups of required arguments
本文介绍了python argparse:使用两组必需的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个可以在两种模式下接受参数的 python 程序:
I have a python program that can take arguments in two modes :
要么 (a) 要么 (b AND c AND d).
EITHER (a) OR (b AND c AND d).
我已经查看了 add_mutually_exclusive_group
但它不允许有一个包含所需参数列表的子组
I've looked at add_mutually_exclusive_group
but it does not allow to have one subgroup with a list of required arguments
有什么想法吗?
推荐答案
你可以让第二种模式需要 3 个参数,像这样:
You could make the second mode require 3 arguments, like this:
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--mode1',
metavar='A',
)
group.add_argument(
'--mode2',
nargs=3,
metavar=('B', 'C', 'D'),
)
args = parser.parse_args()
print(args)
示例输出:
$ ./test.py -h
usage: test.py [-h] (--mode1 A | --mode2 B C D)
optional arguments:
-h, --help show this help message and exit
--mode1 A
--mode2 B C D
$
$ # Valid arguments
$ ./test.py --mode1 foo
Namespace(mode1='foo', mode2=None)
$ ./test.py --mode2 foo bar baz
Namespace(mode1=None, mode2=['foo', 'bar', 'baz'])
$
$ # Invalid arguments
$ ./test.py --mode1 foo bar
usage: test.py [-h] (--mode1 A | --mode2 B C D)
test.py: error: unrecognized arguments: bar
$ ./test.py --mode2 foo bar
usage: test.py [-h] (--mode1 A | --mode2 B C D)
test.py: error: argument --mode2: expected 3 argument(s)
$ ./test.py
usage: test.py [-h] (--mode1 A | --mode2 B C D)
test.py: error: one of the arguments --mode1 --mode2 is required
这篇关于python argparse:使用两组必需的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文