I am trying to use the Python library Click, but struggle to get an example working. I defined two groups, one of which (group2
) is meant to handle common parameters for this group of commands. What I want to achieve is that those common parameters get processed by the group function (group2
) and assigned to the context variable, so they can be used by the actual commands.
A use case would be a number of commands that require username and password, while some others don't (not even optionally).
This is the code
import click
@click.group()
@click.pass_context
def group1(ctx):
pass
@click.group()
@click.option('--optparam', default=None, type=str)
@click.option('--optparam2', default=None, type=str)
@click.pass_context
def group2(ctx, optparam):
print 'in group2', optparam
ctx['foo'] = create_foo_by_processing_params(optparam, optparam2)
@group2.command()
@click.pass_context
def command2a(ctx):
print 'command2a', ctx['foo']
@group2.command()
@click.option('--another-param', default=None, type=str)
@click.pass_context
def command2b(ctx, another_param):
print 'command2b', ctx['foo'], another_param
# many more more commands here...
# @group2.command()
# def command2x():
# ...
@group1.command()
@click.argument('argument1')
@click.option('--option1')
def command1(argument1, option1):
print 'In command2', argument1, option1
cli = click.CommandCollection(sources=[group1, group2])
if __name__ == '__main__':
cli(obj={})
And this is the result when using command2:
$ python cli-test.py command2 --optparam=123
> Error: no such option: --optparam`
What's wrong with this example. I tried to follow the docs closely, but opt-param
doesn't seem to be recognised.
--optparam
to modify the group or the command? In the case of the above code you are applying the option to the group, but in all use cases you are using it in the command. Why not simply apply the option to the command directly? – Kareliagroup2
commands that have mainly common options. Those options should be evaluated and processed and based on that the context variable should be updated (ideally in the group and passed as context to the commands). I'll update the example soon. – Whim