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.

3
  • we can't understand much if you don't really explain more. Commented Jun 3, 2020 at 22:03
  • 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. Commented Jun 4, 2020 at 6:51
  • 1
    Does this help? stackoverflow.com/questions/61933678/… 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 choice Commented Jun 4, 2020 at 7:58

2 Answers 2

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

Also works for individual help sections: format_usage, format_help_text, format_options, format_epilog
7

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

1 Comment

You should use formatter.write instead of click.echo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.