Python单击:如何打印有关使用错误的完整帮助详细信息?

时间:2018-11-03 11:25:51

标签: python python-click

我在使用python click作为我的CLI。当我传入错误的参数或标志集时,会弹出一条用法消息。但是,当我使用--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

1 个答案:

答案 0 :(得分:1)

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