Custom help in python click

Viewed 2591

By default, click adds a --help option that outputs a standardised usage text based on the structure of the click commands:

Usage: ...

Options: ...

Commands:
   ...
   ...

How to override this behaviour to have a custom help output ? What I am trying to do is to output a custom message using rich library.

2 Answers

The trick is to create a click.Group class and override format_help method

class RichGroup(click.Group):
    def format_help(self, ctx, formatter):
        sio = io.StringIO()
        console = rich.Console(file=sio, force_terminal=True)
        console.print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:")
        formatter.write(sio.getvalue())

@click.group(cls=RichGroup)
def cli():
    pass

To add to the already accepted answer, you can also subclass click.Command if you only need this custom functionality for a command:

class HelpfulCmd(click.Command):
    def format_help(self, ctx, formatter):
        click.echo("My custom help message")

@click.command(cls=HelpfulCmd)
def mycommand():
    pass
Related