python argparser用于部分选择的多个参数 [英] python argparser for multiple arguments for partial choices
本文介绍了python argparser用于部分选择的多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建一个像这样的argparser:
I create a argparser like this:
parser = argparse.ArgumentParser(description='someDesc')
parser.add_argument(-a,required=true,choices=[x,y,z])
parser.add_argument( ... )
但是,仅对于选项"x"而不是对于选项"y,z",我想要一个附加的REQUIRED参数.例如.
However, only for choice "x" and not for choices "y,z", I want to have an additional REQUIRED argument. For eg.
python test -a x // not fine...needs additional MANDATORY argument b
python test -a y // fine...will run
python test -a z // fine...will run
python test -a x -b "ccc" // fine...will run
如何使用ArgumentParser完成此操作?我知道bash optparser可能实现
How can I accomplish that with ArgumentParser? I know its possible with bash optparser
推荐答案
详细解释子解析器方法:
To elaborate on the subparser approach:
sp = parser.add_subparsers(dest='a')
x = sp.add_parser('x')
y=sp.add_parser('y')
z=sp.add_parser('z')
x.add_argument('-b', required=True)
- 这与您的规范不同,因为不需要
-a
. -
dest='a'
参数确保名称空间中有一个"a"属性. - 通常不需要像'-b'这样的可选内容.子解析器"x"也可以采用所需的位置.
- this differs from your specification in that no
-a
is required. dest='a'
argument ensures that there is an 'a' attribute in the namespace.- normally an optional like '-b' is not required. Subparser 'x' could also take a required positional.
如果必须使用-a
可选选项,则可以进行两步解析
If you must use a -a
optional, a two step parsing might work
p1 = argparse.ArgumentParser()
p1.add_argument('-a',choices=['x','y','z'])
p2 = argparse.ArgumentParser()
p2.add_argument('-b',required=True)
ns, rest = p1.parse_known_args()
if ns.a == 'x':
p2.parse_args(rest, ns)
第三种方法是在事实发生后进行自己的测试.您仍然可以使用argparse错误机制
A third approach is to do your own test after the fact. You could still use the argparse error mechanism
parser.error('-b required with -a x')
这篇关于python argparser用于部分选择的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文