Last Updated: May 29, 2018
·
7.973K
· scott2b

Implementing a help command in Python Click

Click is Armin Ronacher's very cool command-line building library that make short work of building your own CLI in Python. It's really worth checking out: http://click.pocoo.org/

One of click's excellent features is the built-in help mechanism. mycli --help basically comes for free, as well as individual command help: mycli mycommand --help.

A common usage pattern these days, however, is to have a help command that shows the overall help for the application. Click give you the --help option mentioned above, but your users might expect mycli help to work instead.

Say you've defined your cli as a group:

@click.group(context_settings={'help_option_names':['-h','--help']})
def cli():
    """My very cool command-line tool"""
    pass

And various commands that look like this:

@click.command()
def dosomething():
    """Do Something."""
    dosomething()
cli.add_command(dosomething)

Getting a help command to work is as simple as calling get_help on the parent context of the help command context:

@click.command()
@click.pass_context
def help(ctx):
    print(ctx.parent.get_help())
cli.add_command(help)

That's all there is to it!

1 Response
Add your response

Just what I was looking for, thanks.

over 1 year ago ·