创建具有多个参数的命令选择一个

Creating commands with multiple arguments pick one

我正在尝试创建一个基于 Click 的命令行界面,我发现 CLI 就足够了,但是我似乎无法弄清楚我应该如何设计它。到目前为止,我有下面的代码创建了 4 个命令。然而,我理想中想要的是这样的:

commands:
cli.py env delete NAME
cli.py env list
cli.py source delete NAME
cli.py source list

我当前的代码:

@click.group()
@click.version_option()
def cli():
    """First paragraph.
    """

@cli.command()
def list_env():
    "list env"

@cli.command()
def delete_env(name):
    "Delete enviroment"

@cli.command()
def list_source():
    "list source"

def delete_source(name):
    "Delete source"

if __name__ == '__main__':
    cli()

您尝试做的事情可以通过子组来完成。关键是再声明两个组(即:envsource),它们是 cli 的子组,然后是命令(即:listdelete) 将与以下子组相关联:

代码:

import click

@click.group()
@click.version_option()
def cli():
    """First paragraph.
    """

@cli.group()
def env():
    """env sub-command"""

@env.command('list')
def list_():
    click.echo("env list")

@env.command()
@click.argument('name')
def delete(name):
    click.echo("env delete %s" % name)

@cli.group()
def source():
    """source sub-command"""

@source.command('list')
def list_():
    click.echo("source list")

@source.command()
@click.argument('name')
def delete(name):
    click.echo("source delete %s" % name)

测试代码:

if __name__ == '__main__':
    #cli('env list'.split())
    cli('env delete a_name'.split())
    #cli('source list'.split())
    #cli('source delete a_name'.split())

结果:

env delete a_name