Python Click-提供配置文件中的参数和选项 [英] Python Click - Supply arguments and options from a configuration file

查看:409
本文介绍了Python Click-提供配置文件中的参数和选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下程序:

#!/usr/bin/env python
import click

@click.command()
@click.argument("arg")
@click.option("--opt")
@click.option("--config_file", type=click.Path())
def main(arg, opt, config_file):
    print("arg: {}".format(arg))
    print("opt: {}".format(opt))
    print("config_file: {}".format(config_file))
    return

if __name__ == "__main__":
    main()

我可以使用通过命令行提供的参数和选项来运行它.

I can run it with the arguments and options provided through command line.

$ ./click_test.py my_arg --config_file my_config_file
arg: my_arg
opt: None
config_file: my_config_file

如何为--config_file提供配置文件(在ini?yaml?py?json?中)并接受内容作为参数和选项的值?

How do I provide a configuration file (in ini? yaml? py? json?) to --config_file and accept the content as the value for the arguments and options?

例如,我要包含my_config_file

opt: my_opt

并显示程序的输出:

$ ./click_test.py my_arg --config_file my_config_file
arg: my_arg
opt: my_opt
config_file: my_config_file

我发现了callback函数,该函数看起来很有用,但找不到将同级参数/选项修改为同一函数的方法.

I've found the callback function which looked to be useful but I couldn't find a way to modify the sibling arguments/options to the same function.

推荐答案

这可以通过使用click.Command.invoke()方法来完成,例如:

This can be done by over riding the click.Command.invoke() method like:

def CommandWithConfigFile(config_file_param_name):

    class CustomCommandClass(click.Command):

        def invoke(self, ctx):
            config_file = ctx.params[config_file_param_name]
            if config_file is not None:
                with open(config_file) as f:
                    config_data = yaml.safe_load(f)
                    for param, value in ctx.params.items():
                        if value is None and param in config_data:
                            ctx.params[param] = config_data[param]

            return super(CustomCommandClass, self).invoke(ctx)

    return CustomCommandClass

使用自定义类:

然后使用自定义类,将其作为cls参数传递给命令装饰器,例如:

Using Custom Class:

Then to use the custom class, pass it as the cls argument to the command decorator like:

@click.command(cls=CommandWithConfigFile('config_file'))
@click.argument("arg")
@click.option("--opt")
@click.option("--config_file", type=click.Path())
def main(arg, opt, config_file):

测试代码:

# !/usr/bin/env python
import click
import yaml

@click.command(cls=CommandWithConfigFile('config_file'))
@click.argument("arg")
@click.option("--opt")
@click.option("--config_file", type=click.Path())
def main(arg, opt, config_file):
    print("arg: {}".format(arg))
    print("opt: {}".format(opt))
    print("config_file: {}".format(config_file))


main('my_arg --config_file config_file'.split())

测试结果:

arg: my_arg
opt: my_opt
config_file: config_file

这篇关于Python Click-提供配置文件中的参数和选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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