argparse - 使用附加参数定义自定义操作或类型

dpu*_*ier 2 python argparse

我正在开发一个包含多个 python 脚本的工具箱。对于其中的一些参数,某些参数可能是数值。根据脚本的不同,有些可能要求值 v 介于 -1 和 1 之间,或者 0 和 1 之间,或者 1 和 10 之间,或者...一个例子是输出图表中的页面宽度,它应该始终为正值。

我可以随时检查 v 是否在要求的范围内。我还可以使用 argparse 为每个范围定义一个操作或类型。给出了使用新类型的示例:

def positive_num(a_value):
    """Check a numeric positive."""
    if not a_value > 0:
        raise argparse.ArgumentTypeError("Should be positive.")
    return a_value 
Run Code Online (Sandbox Code Playgroud)

稍后将其添加到解析器中:

parser_grp.add_argument('-pw', '--page-width',
                        help='Output pdf file width (e.g. 7 inches).',
                        type=positive_num,
                        default=None,
                        required=False)
Run Code Online (Sandbox Code Playgroud)

现在,如果该值是相关系数(或范围内的任何值),则可以使用操作或类型来编写更通用的内容:

def ranged_num(a_value, lowest=-1, highest=1):
    """Check a numeric is in expected range."""
    if not (a_value >= lowest and a_value <= highest):
        raise argparse.ArgumentTypeError("Not in range.")
    return a_value 
Run Code Online (Sandbox Code Playgroud)

稍后可以添加如下内容:

parser_grp.add_argument('-c', '--correlation',
                        help='A value for the correlation coefficient',
                        type=ranged_num(-1,1),
                        default=None,
                        required=False)
Run Code Online (Sandbox Code Playgroud)

我尝试了多种方法但没有成功。

谢谢

jon*_*rpe 5

根据文档

type=可以采用任何采用单个字符串参数并返回转换后的值的可调用函数

因此,要像 一样使用它type=ranged_num(-1,1),您的ranged_num函数必须返回一个函数本身。返回函数(或接受函数作为参数,或两者兼而有之)的函数通常称为“高阶函数”。

这是一个最小的例子:

def ranged_num(lowest=-1, highest=1):
    """Check a numeric is in expected range."""
    def type_func(a_value):
        a_value = int(a_value)  # or "float"; you could also have error handling here
        if not (a_value >= lowest and a_value <= highest):  # I'd rewrite this to an "or"
            raise argparse.ArgumentTypeError("Not in range.")
        return a_value
    return type_func
Run Code Online (Sandbox Code Playgroud)

现在ranged_num创建并返回一个函数 ,type_func该函数负责处理来自命令行的字符串。