Custom help in python click
Asked Answered
C

2

7

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.

Chericheria answered 3/6, 2020 at 21:4 Comment(3)
we can't understand much if you don't really explain more.Od
The beauty of click is that it make sense out of the box. I think if you want to extend click, you might want to write an extension. Have a look at github.com/click-contrib perhaps you can find another project that uses the API you need.Judaist
Does this help? #61934178 It explains how to override the help message for a group, and it's probably the best place for you to customise the help message using a library of your choiceImplicatory
C
15

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
Chericheria answered 17/6, 2020 at 20:30 Comment(1)
Also works for individual help sections: format_usage, format_help_text, format_options, format_epilogChericheria
B
6

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
Buckshee answered 25/9, 2020 at 17:11 Comment(1)
You should use formatter.write instead of click.echoSpangle

© 2022 - 2024 — McMap. All rights reserved.