Search code examples
pythoncommand-line-interfacepython-click

python click detailed help for commands


Is there a way to get separate detailed help for click commands? For example to print the options/arguments for that command.

Example for this cli:

import click

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

@cli.command()
@click.argument('arg1')
@click.option('--option1', default=1)
def cmd1(arg1):
    print(arg1)

if __name__ == '__main__':
    cli()

The default help only gives this:

> python cli.py --help

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

Options:
  --help  Show this message and exit.

Commands:
  cmd1

I would like something like this:

> python cli.py --help cmd1

...
Command cmd1
Arguments:
    arg1
Options:
    --option1
....

Is this possible?


Solution

  • If you put the --help after the command you will get what you are after.

    python cli.py cmd1 --help
    

    Test Code:

    import click
    
    @click.group()
    def cli():
        pass
    
    @cli.command()
    @click.argument('arg1')
    @click.option('--option1', default=1)
    def cmd1(arg1):
        print(arg1)
    
    
    if __name__ == "__main__":
        commands = (
            'cmd1 --help',
            '--help',
            '',
        )
    
        import sys, time
    
        time.sleep(1)
        print('Click Version: {}'.format(click.__version__))
        print('Python Version: {}'.format(sys.version))
        for cmd in commands:
            try:
                time.sleep(0.1)
                print('-----------')
                print('> ' + cmd)
                time.sleep(0.1)
                cli(cmd.split())
    
            except BaseException as exc:
                if str(exc) != '0' and \
                        not isinstance(exc, (click.ClickException, SystemExit)):
                    raise
    

    Results:

    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)]
    -----------
    > cmd1 --help
    Usage: test.py cmd1 [OPTIONS] ARG1
    
    Options:
      --option1 INTEGER
      --help             Show this message and exit.
    -----------
    > --help
    Usage: test.py [OPTIONS] COMMAND [ARGS]...
    
    Options:
      --help  Show this message and exit.
    
    Commands:
      cmd1
    -----------
    > 
    Usage: test.py [OPTIONS] COMMAND [ARGS]...
    
    Options:
      --help  Show this message and exit.
    
    Commands:
      cmd1