Python argparse:如何检测重复的可选参数? [英] Python argparse : how to detect duplicated optional argument?
问题描述
我正在使用带有可选参数的argparse,但我想避免使用类似以下内容的脚本:script.py -a 1 -b -a 2 在这里,我们有两个可选参数"a",并且仅返回第二个参数.我想获取两个值或获取错误消息. 我应该如何定义参数?
I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2 Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message. How should I define the argument ?
这是代码:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='alpha', action='store', nargs='?')
parser.add_argument('-b', dest='beta', action='store', nargs='?')
params, undefParams = self.parser.parse_known_args()
推荐答案
append
操作将收集重复使用的值在列表中
append
action will collect the values from repeated use in a list
parser.add_argument('-a', '--alpha', action='append')
生成args
命名空间,例如:
namespace(alpha=['1','3'], b='4')
解析后,您可以检查args.alpha
,并接受或抱怨值的数量. parser.error('repeated -a')
可用于发布argparse样式错误消息.
After parsing you can check args.alpha
, and accept or complain about the number of values. parser.error('repeated -a')
can be used to issue an argparse style error message.
您可以在自定义Action类中实现类似的功能,但这需要了解此类的基本结构和操作.我想在Action中做不到的任何事情,在之后的附加列表中也做不到.
You could implement similar functionality in a custom Action class, but that requires understanding the basic structure and operation of such a class. I can't think anything that can be done in an Action that can't just as well be done in the appended list after.
https://stackoverflow.com/a/23032953/901925 是不重复的自定义Action
.
为什么要使用带有这样标记的参数的nargs='?'
?没有const
参数,这几乎是没有用的(请参阅文档中的nargs=?
部分).
Why are you using nargs='?'
with flagged arguments like this? Without a const
parameter this is nearly useless (see the nargs=?
section in the docs).
另一个类似的方法: Python argparse的nargs行为不正确
这篇关于Python argparse:如何检测重复的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!