Python Click - Supply arguments and options from a configuration file Python Click - Supply arguments and options from a configuration file python python

Python Click - Supply arguments and options from a configuration file


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 pythonimport clickimport 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_argopt: my_optconfig_file: config_file