Python点击:自定义错误信息

Python Click: custom error message

我用的是极品Python Click library for handling command line options in my tool. Here's a simplified version of my code (full script here):

@click.command(
    context_settings = dict( help_option_names = ['-h', '--help'] )
)
@click.argument('analysis_dir',
                 type = click.Path(exists=True),
                 nargs = -1,
                 required = True,
                 metavar = "<analysis directory>"
)

def mytool(analysis_dir):
   """ Do stuff """

if __name__ == "__main__":
    mytool()

如果有人在没有任何标志的情况下运行命令,他们会收到默认的点击错误消息:

$ mytool

Usage: mytool [OPTIONS] <analysis directory>

Error: Missing argument "analysis_dir".

这很好,但我很想告诉(非常)新手用户使用帮助标志可以获得更多帮助。换句话说,当命令无效时,在错误消息中添加自定义语句告诉人们尝试 mytool --help 以获取更多信息。

有没有简单的方法来做到这一点?我知道我可以删除 required 属性并在主函数中处理这个逻辑,但是对于这样一个小的添加感觉有点老套。

python-click 中大多数错误的消息构造由 UsageError class: click.exceptions.UsageError.show 的显示方法处理。

因此,如果您重新定义此方法,您将能够创建自己的自定义错误消息。下面是一个自定义示例,它将帮助菜单附加到任何回答此 SO question:

的错误消息
def modify_usage_error(main_command):
    '''
        a method to append the help menu to an usage error

    :param main_command: top-level group or command object constructed by click wrapper 
    :return: None
    '''

    from click._compat import get_text_stderr
    from click.utils import echo
    def show(self, file=None):
        import sys
        if file is None:
            file = get_text_stderr()
        color = None
        if self.ctx is not None:
            color = self.ctx.color
            echo(self.ctx.get_usage() + '\n', file=file, color=color)
        echo('Error: %s\n' % self.format_message(), file=file, color=color)
        sys.argv = [sys.argv[0]]
        main_command()

    click.exceptions.UsageError.show = show

一旦你定义了你的主要命令,你就可以运行修改脚本:

import click
@click.group()
def cli():
    pass

modify_usage_error(cli)

除了使用错误之外,是否有 运行次调用 ClickException 的情况我还没有研究过。如果有,那么您可能需要修改您的自定义错误处理程序以在添加行 click.exceptions.ClickException.show = show 之前首先检查 ctx 是否是一个属性,因为在初始化时似乎没有向 ctx 提供 ClickException。