Search code examples
pythonpython-click

HelpFormatter in Click


I am using click within a local module and I would like to adjust how the help is displayed:

Currently output with --help:

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

Options:
  --help  Show this message and exit.

Commands:
  foo     Foo is a program very nice and pretty...

By default the prog name is __main__.py and the text is trimmed to 78 chars.

I discovered that this can be adjusted using the HelpFormatter class. But I don't know how to use it in this context.

Current Code:

import click

@click.group()
def main(ctx):
   pass

@main.command()
def foo():
   pass

click.CommandCollection(sources=[main])()

Expected output:

Usage: my_module_name [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  foo     Foo is a program very nice and pretty and this sentence is very long.

Solution

  • If you are trying to to avoid the truncation of the help string, this can be accomplished via the short_help parameter. short_help is generally derived from help but truncated. If passed explicitly, the entire string will be displayed.

    To display the string my_module_name, that can be passed under the parameter prog_name

    Test Code:

    import click
    
    @click.group()
    def main(ctx):
       pass
    
    @main.command(short_help='Foo is a program very nice and pretty and '
                             'this sentence is very long.')
    def foo():
       pass
    
    main(['--help'], prog_name='my_module_name')
    

    Results of short_help:

    Usage: my_module_name [OPTIONS] COMMAND [ARGS]...
    
    Options:
      --help  Show this message and exit.
    
    Commands:
      foo  Foo is a program very nice and pretty and this sentence is very long.