Python 点击:如何打印有关使用错误的完整帮助详情?

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

我正在为我的 CLI 使用 python click。当我传入错误的参数或标志集时,会弹出一条用法消息。但是,当我使用 --help 标志时,会弹出一条更详细的用法消息,其中包含所有选项和参数的列表。有没有办法更改默认行为,以便使用错误打印完整详细的帮助?

例如,缺少参数打印

mycli foo
Usage: mycli foo [OPTIONS] MY_ARG

Error: Missing argument "my_arg".

但是添加 --help 打印出

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.

命令大致是这样实现的

@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

可以通过猴子修补来完成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