【问题标题】:Python Click: How to print full help details on usage error?Python Click:如何打印有关使用错误的完整帮助详细信息?
【发布时间】:2018-11-03 11:25:51
【问题描述】:

我正在为我的 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

【问题讨论】:

  • 如果您要举例说明如何构建命令,这将更容易回答。有多种方法可以构建上述内容,它们的解决方案会略有不同。

标签: python python-click


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2021-12-27
    • 2011-11-21
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多