user2770034
user2770034

Reputation: 256

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.

Upvotes: 7

Views: 5838

Answers (2)

dancow
dancow

Reputation: 3388

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

Upvotes: 7

user2770034
user2770034

Reputation: 256

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

Upvotes: 15

Related Questions