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

时间:2017-07-12 13:31:02

标签: python python-click

我试图创建一个基于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()

1 个答案:

答案 0 :(得分:0)

您尝试做的事情可以通过子组完成。关键是要声明另外两个组(即envsource),它们是cli的子组,然后是命令(即:list和{{ 1}})将与子组相关联,如:

代码:

delete

测试代码:

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