gpt4 book ai didi

python - argparse 选择允许值的结构

转载 作者:太空狗 更新时间:2023-10-29 18:19:24 27 4
gpt4 key购买 nike

使用关于 Python dependencies between groups using argparseargparse ,我有一个解析器的某个解析器组的参数部分 - 例如:

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

非常感谢大家的帮助!

最佳答案

您可以定义一个自定义类型,如果字符串与您需要的格式不匹配。

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,))

关于python - argparse 选择允许值的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14665234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com