python - 如何处理子组帮助消息

标签 python command-line-interface python-click

我正在尝试了解有关 Click 的一些实现细节。我有以下示例代码:

#cli.py

import click


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


@cli.group()
def show():
    """ Define the environment of the product """
    pass


@show.command()
def name():
    click.echo("run show name command")


@show.command()
def height():
    click.echo("run show height command")


if __name__ == "__main__":
    cli()

使用此代码,nameheightshow 的子命令团体。然而,从语义上来说,这实际上没有意义。它们更像是“show”命令的参数

我知道我可以有一个带有“attribute”参数的命令,我可以根据“attribute”的字符串值调用不同的函数。然而,我觉得一旦“属性”有多种可能性,维护起来就会很乏味。

我相信如果我能够编辑帮助消息,我仍然可以使用上述结构。当我运行cli.py show --help时,我收到命令组的默认帮助消息:

Usage: cli.py show [OPTIONS] COMMAND [ARGS]...

  Define the environment of the product

Options:
  --help  Show this message and exit.

Commands:
  height
  name

有没有办法编辑帮助消息以将“命令”更改为“参数”?我知道如何更改 click.group() 装饰器中的使用语句,但我不确定如何修改帮助消息本身。

我想要实现的帮助信息如下:

Usage: cli.py show [OPTIONS] ARG

  Define the environment of the product

Options:
  --help  Show this message and exit.

Arguments:
  height
  name

这样的事情可能吗?

我正在使用 python3 和 Click 6.7

最佳答案

您可以通过使用组的自定义类来更改子命令帮助给出的消息。可以通过继承 click.Group 并更改 format_commands() 方法来创建自定义类,例如:

自定义类:

class HelpAsArgs(click.Group):
    # change the section head of sub commands to "Arguments"

    def format_commands(self, ctx, formatter):
        rows = []
        for subcommand in self.list_commands(ctx):
            cmd = self.get_command(ctx, subcommand)
            if cmd is None:
                continue

            help = cmd.short_help or ''
            rows.append((subcommand, help))

        if rows:
            with formatter.section('Arguments'):
                formatter.write_dl(rows)

测试代码:

import click

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

@cli.group(cls=HelpAsArgs)
def show():
    """ Define the environment of the product """
    pass

@show.command()
def name():
    click.echo("run show name command")

@show.command()
def height():
    click.echo("run show height command")

if __name__ == "__main__":
    commands = (
        'show',
        'show --help',
        '--help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for command in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + command)
            time.sleep(0.1)
            cli(command.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> show
Usage: test.py show [OPTIONS] COMMAND [ARGS]...

  Define the environment of the product

Options:
  --help  Show this message and exit.

Arguments:
  height
  name
-----------
> show --help
Usage: test.py show [OPTIONS] COMMAND [ARGS]...

  Define the environment of the product

Options:
  --help  Show this message and exit.

Arguments:
  height
  name
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  show  Define the environment of the product

关于python - 如何处理子组帮助消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952684/

相关文章:

python - 从类定义中的列表推导式访问类变量

python - 从一列复制字符串的一部分并将其放入新的 Pandas 列中

python - 使用 Python boto3 对大量存储桶进行 S3 默认服务器端加密

database - 在 Redis-cli 中设置自定义命令

python - 是否有更惯用的方法来使用 Python 的 Click 获取参数列表?

python - 为什么 str.translate 在 Python 3 中不起作用?

python - tkinter wraplength 单位是像素吗?

go - 你如何在 Go YAML 中编码换行符?

python - 如何将多个参数列表传递给@click.option

python - 单击 : Is it possible to pass multiple inputs to CliRunner. 调用?