Given the following program:
#!/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
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?
For instance, I want my_config_file
to contain
opt: my_opt
and have the output of the program show:
$ ./click_test.py my_arg --config_file my_config_file
arg: my_arg
opt: my_opt
config_file: my_config_file
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.
This can be done by over riding the
click.Command.invoke()
method like:Custom Class:
Using Custom Class:
Then to use the custom class, pass it as the cls argument to the command decorator like:
Test Code:
Test Results: