I want to pass an unlimited number of options to a click CLI. I don't know Option names either. I'm getting around this issue by using an option named conf
. It accepts a string that is assumed to represent a JSON object.
What I've done:
@click.command()
@click.option('--conf', type=str)
def dummy(conf):
click.echo('dummy param {}'.format(conf))
How I use it:
>python main.py dummy --conf='{"foo": "bar", "fizz": "buzz"}'
What I want to do:
@click.command()
#some magic stuff
def dummy(**kwargs):
click.echo('dummy param {}'.format(**kwargs))
How I want to use it:
>python main.py dummy --foo=bar --fizz=buzz
You can hook the parser and make it aware of each option given from the command line like:
Custom Command Class:
Using the Custom Class:
To use the custom class, just pass the class to the
click.command()
decorator like:How does this work?
This works because click is a well designed OO framework. The
@click.command()
decorator usually instantiates aclick.Command
object but allows this behavior to be over-ridden with thecls
parameter. So it is a relatively easy matter to inherit fromclick.Command
in our own class and over ride the desired methods.In this case, we override
make_parser()
and replace the option dicts with adict
class of our own. In ourdict
we override the__contains__()
magic method, and in it we populate the parser with an option matching the name that is being looked for, if that name does not already exist.Test Code:
Results: