Python Click - Supply arguments and options from a configuration file

前端 未结 1 1709
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 13:40

Given the following program:

#!/usr/bin/env python
import click

@click.command()
@click.argument(\"arg\")
@click.option(\"--opt\")
@click.option(\"--config_file         


        
相关标签:
1条回答
  • 2021-02-05 13:59

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

    Custom Class:

    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
    

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

    Test Code:

    # !/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())
    

    Test Results:

    arg: my_arg
    opt: my_opt
    config_file: config_file
    
    0 讨论(0)
提交回复
热议问题