argparse 允许值的选择结构
在使用 argparse
这个工具时,我有一个参数属于某个解析器组的部分,比如说:
group_simulate.add_argument('-P',
help='simulate FC port down',
nargs=1,
metavar='fc_port_name',
dest='simulate')
我想知道怎么用 choices 来限制选择的参数,要求这些参数符合下面的结构:
1:m:"number between 1 and 10":p:"number between 1 and 4"
我尝试过使用范围选项,但找不到创建一个可接受的选择列表的方法。
合法的参数示例:
test.py -P 1:m:4:p:2
不合法的参数示例:
test.py -P 1:p:2
test.py -P abvds
非常感谢大家的帮助!
2 个回答
0
如果我理解你的问题没错的话,你只是想要找:
group_simulate.add_argument('-P',
help='simulate FC port down',
type=int,
metavar='fc_port_name',
dest='simulate',
choices=range(1, 10)) # answer
22
你可以定义一个自定义类型,如果字符串不符合你需要的格式,就会抛出一个 argparse.ArgumentTypeError
错误。
def SpecialString(v):
fields = v.split(":")
# Raise a value error for any part of the string
# that doesn't match your specification. Make as many
# checks as you need. I've only included a couple here
# as examples.
if len(fields) != 5:
raise argparse.ArgumentTypeError("String must have 5 fields")
elif not (1 <= int(fields[2]) <= 10):
raise argparse.ArgumentTypeError("Field 3 must be between 1 and 10, inclusive")
else:
# If all the checks pass, just return the string as is
return v
group_simulate.add_argument('-P',
type=SpecialString,
help='simulate FC port down',
nargs=1,
metavar='fc_port_name',
dest='simulate')
更新:这里有一个完整的自定义类型来检查值。所有的检查都是通过正则表达式来完成的,不过如果有任何部分出错,它只会给出一个通用的错误信息。
def SpecialString(v):
import re # Unless you've already imported re previously
try:
return re.match("^1:m:([1-9]|10):p:(1|2|3|4)$", v).group(0)
except:
raise argparse.ArgumentTypeError("String '%s' does not match required format"%(v,))