Jesse Shieh
Jesse Shieh

Reputation: 4850

Python Click: How to print full help details on usage error?

I'm using python click for my CLI. When I pass in the wrong set of arguments or flags, a usage message pops up. However, when I use the --help flag a more detailed usage message pops up with a list of all options and arguments. Is there a way to change the default behavior so that a usage error prints the full detailed help?

For example, a missing argument prints

mycli foo
Usage: mycli foo [OPTIONS] MY_ARG

Error: Missing argument "my_arg".

But adding --help prints

mycli foo --help
Usage: mycli foo [OPTIONS] MY_ARG

  Long and useful description of the command and stuff.

Options:
  -h, --help  Show this message and exit.

The command is implemented roughly like so

@click.group()
@click.pass_context
def cli(ctx):
    ctx.obj = {}

@cli.command()
@click.argument('my_arg')
@click.pass_context
@report_errors
def foo(ctx, my_arg):
  # some stuff here

Upvotes: 4

Views: 2433

Answers (1)

r-m-n
r-m-n

Reputation: 15090

it could be done by monkey-patching UsageError

import click
from click.exceptions import UsageError
from click._compat import get_text_stderr
from click.utils import echo


def _show_usage_error(self, file=None):
    if file is None:
        file = get_text_stderr()
    color = None
    if self.ctx is not None:
        color = self.ctx.color
        echo(self.ctx.get_help() + '\n', file=file, color=color)
    echo('Error: %s' % self.format_message(), file=file, color=color)


UsageError.show = _show_usage_error


@click.group()
@click.pass_context
def cli(ctx):
    ctx.obj = {}

@cli.command()
@click.argument('my_arg')
@click.pass_context
@report_errors
def foo(ctx, my_arg):
  # some stuff here

Upvotes: 2

Related Questions