argparse选择允许值的结构

Eli*_*lia 10 python argparse

使用argparse相对于使用argparse组之间的Python依赖性,我有一个分析器的一些解析器组的参数部分-例如:

group_simulate.add_argument('-P',
                            help='simulate FC port down',
                            nargs=1,
                            metavar='fc_port_name',
                            dest='simulate')
Run Code Online (Sandbox Code Playgroud)

如何使用选项选项限制为下一个结构的参数列表:

1:m:"number between 1 and 10":p:"number between 1 and 4"
Run Code Online (Sandbox Code Playgroud)

我试图使用范围选项,但我找不到一种方法来创建一个可接受的选项列表

示例:法律参数:

test.py -P 1:m:4:p:2
Run Code Online (Sandbox Code Playgroud)

不合法的参数:

test.py -P 1:p:2
test.py -P abvds
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助!

che*_*ner 20

您可以定义一个自定义类型,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')
Run Code Online (Sandbox Code Playgroud)

更新:这是一个完整的自定义类型来检查值.所有检查都在正则表达式中完成,但如果任何部分出错,它只会给出一条通用错误消息.

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,))
Run Code Online (Sandbox Code Playgroud)