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

标签 python python-click

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/

相关文章:

python - del语句是否打开内存?

python - 无法在 Jupyter Notebook 中导入 tensorflow

python - 在 OpenGL 中围绕坐标旋转四边形

python - 动态指定选项和参数

python - 为什么我的 Python Click 命令不起作用?

python - 诗歌管理python包CLI

python - 如何将 swig/pybind11 C++ 项目放到 pypi 上

python - 程序退出时MySQL行被删除

python - 一个没有名字的命令,在 Click

Python click,你能把 -h 作为别名吗