允许值的argparse选择结构 [英] argparse choices structure of allowed values

查看:70
本文介绍了允许值的argparse选择结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using argparse in relation to Python dependencies between groups using argparse, I have an argument part of some parser group of a parser - for example:

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

如何使用选择来限制选择到下一个结构的参数列表:

How it's possible to use the choices to limit the choices to a list of parameters of the next structure:

1:m:"number between 1 and 10":p:"number between 1 and 4"

我尝试使用range选项,但找不到创建可接受的选项列表的方法

I have tried to use the range option but I couldn't find a way to create a list of choices that are acceptable

示例: 合法参数:

test.py -P 1:m:4:p:2

非合法参数:

test.py -P 1:p:2
test.py -P abvds

非常感谢您的帮助!

推荐答案

您可以定义一个自定义类型,如果字符串将引发argparse.ArgumentTypeError 与您所需的格式不匹配.

You can define a custom type that will raise an argparse.ArgumentTypeError if the string doesn't match the format you need.

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

更新:这是一个完整的自定义类型,用于检查值.所有检查均已完成 在正则表达式中,尽管它只给出一条通用错误消息 如果有什么地方不对.

UPDATE: here's a full custom type to check the value. All checking is done in the regular expression, although it only gives one generic error message if any part is wrong.

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

这篇关于允许值的argparse选择结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆