I try to build a command line application that has several single commands with different options, but also a general command which should execute every single command as well.
The code looks currently like this:
import click
@click.group()
def cli():
...
@cli.command('mod1', context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.argument('arg1')
@click.argument('arg2')
@click.option('--option1')
@click.pass_context
def mod1(ctx, arg1, arg2, option1):
print('Running mod1')
print(ctx.params)
print(ctx.args)
@cli.command('mod2', context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.argument('arg1')
@click.argument('arg2')
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def mod2(ctx, arg1, arg2, option1, option2):
print('Running mod2')
print(ctx.params)
@cli.command('mod3', context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.argument('arg1')
@click.pass_context
def mod3(ctx, arg1):
print('Running mod3')
print(ctx.params)
function_mapping = {
'mod1': mod1,
'mod2': mod2,
'mod3': mod3,
}
@cli.command('all', context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.argument('arg1')
@click.argument('arg2')
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def main(ctx, arg1, arg2, option1, option2):
print('Running all commands')
print(ctx.params)
print(ctx.args)
for mod in function_mapping:
ctx.forward(function_mapping[mod])
if __name__ == '__main__':
cli()
The problem is, that whenever mod1
is executed, the script fails with the error message TypeError: mod1() got an unexpected keyword argument 'option2'
. According to this link, paragraph 1, this should work and extra arguments are captured to ctx.args
.
Click version used here is 8.0.4, Python 3.8.10.
Any ideas or hints on this? Many thinks in advance.
EDIT
Is has something to do with ctx.forward
. If I specify mod1
as command and add any other option, it works and those unknown options are seen in ctx.args
.