Search code examples
pythonpython-click

Custom help in python click


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.


Solution

  • 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