点击:“获得了意外的额外参数";传递字符串时 [英] Click: "Got unexpected extra arguments" when passing string

查看:588
本文介绍了点击:“获得了意外的额外参数";传递字符串时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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将字符串参数传递了一个字符.打印参数显示正确的结果.

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

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

PS: KEYS dictionary defined and working as expected.

推荐答案

弄清楚了这一点.我必须传递一个上下文并从那里调用它,而不仅仅是调用一个函数:

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

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

来自文档:

有时候,从另一个命令中调用一个命令可能会很有趣 命令.这是通常不鼓励使用Click的模式, 但仍然可能.为此,您可以使用Context.invoke() 或Context.forward()方法.

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.

它们的工作方式类似,但是区别在于Context.invoke() 只是使用您作为参数提供的参数调用另一个命令 调用方,而Context.forward()则从 当前命令.两者都接受命令作为第一个参数,并且 所有其他一切都会按您期望的那样继续传递.

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()

@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)

以及它的外观:

$ cli dist
Count: 1
Count: 42

这篇关于点击:“获得了意外的额外参数";传递字符串时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆