Jesse Shieh
Jesse Shieh

Reputation: 4850

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

I have a python click CLI. When I pass --help to any command it prints a help message which I love. I've found that many users these days are typing

mycli help foo

instead of

mycli foo --help

Is there a way to make the former work just like the latter in a generic manner for all commands?

The command is implemented roughly like so

@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

Upvotes: 5

Views: 3964

Answers (1)

jwodder
jwodder

Reputation: 57470

click.Command objects have a get_help() method that returns their --help string. Combining this with the group's get_command() method for looking up subcommands, something like this should work (untested):

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

Upvotes: 6

Related Questions