Benjamin Dean Benjamin Dean - 1 year ago 256
Python Question

Click: "Got unexpected extra arguments" when passing string

import click

@click.argument("namespace", nargs=1)
def process(namespace):

def run():
for namespace in KEYS.iterkeys():

run('some string')

Error: Got unexpected extra arguments (o m e s t r i n g)

As if Click passes string argument by one character. Printing an argument shows correct result.

PS: KEYS dictionary defined and working as expected.

Answer Source

Figured this out. Instead of just calling a function, I must pass a context and call it from there:

def run():
    for namespace in KEYS.iterkeys():
        ctx.invoke(process, namespace=namespace)

From the docs:

Sometimes, it might be interesting to invoke one command from another command. This is a pattern that is generally discouraged with Click, but possible nonetheless. For this, you can use the Context.invoke() or Context.forward() methods.

They work similarly, but the difference is that Context.invoke() merely invokes another command with the arguments you provide as a caller, whereas Context.forward() fills in the arguments from the current command. Both accept the command as the first argument and everything else is passed onwards as you would expect.


cli = click.Group()

@click.option('--count', default=1)
def test(count):
    click.echo('Count: %d' % count)

@click.option('--count', default=1)
def dist(ctx, count):
    ctx.invoke(test, count=42)

And what it looks like:

$ cli dist
Count: 1
Count: 42
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download