Click "Receive unexpected optional arguments" when passing a string

import click @cli.command() @click.argument("namespace", nargs=1) def process(namespace): ..... @cli.command() def run(): for namespace in KEYS.iterkeys(): process(namespace) 

Running run('some string') calls:

Error: Got unexpected extra arguments (omestring)

It is as if Click is passing a string argument with a single character. Printing an argument shows the correct result.

PS: KEYS Dictionary is defined and works as expected.

+5
source share
1 answer

Figured it out. Instead of just calling a function, I have to pass the context and call it from there:

 @cli.command() @click.pass_context def run(): for namespace in KEYS.iterkeys(): ctx.invoke(process, namespace=namespace) 

From docs :

Sometimes it may be interesting to call one command from another command. This is a template that is usually not recommended with Click, but is possible nonetheless. You can use Context.invoke () or Context.forward () for this.

They work similarly, but the difference is that Context.invoke () just calls another command with arguments that you provide as the caller, while Context.forward () populates the arguments from the current command. Both take the command as the first argument and everything else is passed forward, as you would expect.

Example:

 cli = click.Group() @cli.command() @click.option('--count', default=1) def test(count): click.echo('Count: %d' % count) @cli.command() @click.option('--count', default=1) @click.pass_context def dist(ctx, count): ctx.forward(test) ctx.invoke(test, count=42) 

And what it looks like:

 $ cli dist Count: 1 Count: 42 
+5
source

Source: https://habr.com/ru/post/1241044/


All Articles