python 错误:使用Click库时获得意外的额外参数

wkyowqbh  于 2023-01-08  发布在  Python
关注(0)|答案(1)|浏览(205)

我尝试使用Python中的Click库来创建命令行界面,但是当我尝试运行脚本时,总是收到以下错误:

Error: Got unexpected extra arguments (hello hello1)

下面是我的代码:

import click

@click.group(name='script')
def cli():
    pass

@cli.command()
def hello1():
    click.echo('Hello, World!')

@cli.command()
def hello2():
    click.echo('Hola, Mundo!')

@cli.command()
@click.argument('function', type=click.Choice(['hello1', 'hello2']))
def hello(function):
    if function == 'hello1':
        hello1()
    elif function == 'hello2':
        hello2()

if __name__ == '__main__':
    cli()

我试图用参数"hello1"或"hello2"调用"hello"函数,但它不起作用。有人能帮我找出问题所在吗?

python script.py hello hello1
hgqdbh6s

hgqdbh6s1#

按照你编写代码的方式,你不应该把hello1hello2定义为命令,如果你简单地去掉装饰器,你的代码就可以正常工作,也就是说,给定:

import click

@click.group(name='script')
def cli():
    pass

def hello1():
    click.echo('Hello, World!')

def hello2():
    click.echo('Hola, Mundo!')

@cli.command()
@click.argument('function', type=click.Choice(['hello1', 'hello2']))
def hello(function):
    if function == 'hello1':
        hello1()
    elif function == 'hello2':
        hello2()

if __name__ == '__main__':
    cli()

我们可以运行:

$ python script.py hello hello1
Hello, World!
$ python script.py hello hello2
Hola, Mundo!

如果希望hello1hello2成为hello的子命令,则需要将hello重新定义为command group,如下所示:

import click

@click.group(name='script')
def cli():
    pass

@cli.group()
def hello():
    pass

@hello.command()
def hello1():
    click.echo('Hello, World!')

@hello.command()
def hello2():
    click.echo('Hola, Mundo!')

if __name__ == '__main__':
    cli()

它支持相同的命令行,但是我们不显式地测试参数,而是依靠click来分派适当的命令。

相关问题