Python 点击:如何实现行为类似于 `--help` 的帮助命令?

Python Click: How to implement a help command that behaves like `--help`?

我有一个 python 单击 CLI。当我将 --help 传递给任何命令时,它会打印一条我喜欢的帮助消息。我发现现在很多用户都在输入

mycli help foo

而不是

mycli foo --help

有没有办法让前者像后者一样对所有命令以通用方式工作?

命令大致是这样实现的

@click.group()
@click.pass_context
def cli(ctx):
    ctx.obj = {}

@cli.command()
@click.argument('my_arg')
@click.pass_context
@report_errors
def foo(ctx, my_arg):
    # some stuff here

click.Command 对象有一个 get_help() method that returns their --help string. Combining this with the group's get_command() 方法来查找子命令,像这样的东西应该可以工作(未经测试):

@cli.command()
@click.argument('subcommand')
@click.pass_context
def help(ctx, subcommand):
    subcommand_obj = cli.get_command(ctx, subcommand)
    if subcommand_obj is None:
        click.echo("I don't know that command.")
    else:
        click.echo(subcommand_obj.get_help(ctx))