gpt4 book ai didi

python - 单击 : "Got unexpected extra arguments" when passing string

转载 作者:太空狗 更新时间:2023-10-29 18:03:43 28 4
gpt4 key购买 nike

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') 产生:

错误:得到意外的额外参数 (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

关于python - 单击 : "Got unexpected extra arguments" when passing string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34904328/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com