允许值的argparse选择结构

允许值的argparse选择结构,第1张

允许值的argparse选择结构

您可以定义一个自定义类型

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5667261.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存