Python 点击​​ : How to print full help details on usage error?

标签 python python-click

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

关于Python 点击​​ : How to print full help details on usage error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130864/

相关文章:

python - ndarray 行不显示每一行

python-click:依赖于另一个选项的选项

python - python中的互斥选项组单击

python - 使用 Python Click 创建分层命令

Python 脚本在一段时间后关闭

python递归方法返回无

python - 如何使用 Paramiko 访问远程主机?

python - 新手 - 具有多个应用程序的 Django 项目 - 无法渲染 View

python - 如何为CommandCollection点击的命令添加帮助?