单击:"Got unexpected extra arguments" 传递字符串时

Click: "Got unexpected extra arguments" when passing string

import click

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

@cli.command()
def run():
    for namespace in KEYS.iterkeys():
        process(namespace)

运行 run('some string') 产生:

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

好像 Click 将字符串参数传递一个字符。打印参数显示正确的结果。

PS:KEYS 字典已定义并按预期工作。

想通了。我不仅要调用一个函数,还必须传递一个上下文并从那里调用它:

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

来自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.

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

tl;dr 从你的论点中删除白色space。

如果其他人正在经历相同的和以上的答案没有澄清或不适合你可能你在我的情况下。

对我来说,这个错误是因为我给出的参数之间有 space 并且 function/module 接受它不允许采用 space 分隔输入,因此输入名称的其余部分被视为单独的参数,导致

"Got unexpected extra arguments" error.

仅在您 运行 的主脚本中使用点击模块可能会有帮助。就我而言,从主要模块以外的模块中删除点击有助于解决此问题。

使用 click 方法调用同名方法时出现此错误:


@cli.command()
@click.argument("namespace", nargs=1)
def process(namespace):
    process("foo")  # <---- HERE

已通过重命名其中一个来解决问题,希望对其他人有所帮助!