Python Click:自定义错误消息 [英] Python Click: custom error message

查看:167
本文介绍了Python Click:自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用出色的 Python Click 库在我的工具中处理命令行选项.这是我的代码的简化版本(完整脚本此处):

I use the excellent 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()

如果有人运行不带任何标志的命令,他们将收到默认的单击错误消息:

If someone runs the command without any flags, they get the default click error message:

$ mytool

Usage: mytool [OPTIONS] <analysis directory>

Error: Missing argument "analysis_dir".

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

This is nice, but I'd quite like to tell (very) novice users that more help is available by using the help flag. In other words, add a custom sentence to the error message when the command is invalid telling people to try mytool --help for more information.

有没有简单的方法可以做到这一点?我知道我可以删除required属性并在main函数中处理此逻辑,但是对于这样的次要添加来说,这有点不客气.

Is there an easy way to do this? I know I could remove the required attribute and handle this logic in the main function, but that feels kind of hacky for such a minor addition.

推荐答案

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

Message construction for most errors in python-click is handled by the show method of the UsageError class: click.exceptions.UsageError.show.

因此,如果您重新定义此方法,则可以创建自己的自定义错误消息.以下是自定义的示例,该示例将帮助菜单附加到回答此 SO的任何错误消息上问题:

So, if you redefine this method, you will be able to create your own customized error message. Below is an example of a customization which appends the help menu to any error message which answers this 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

定义主命令后,即可运行修改器脚本:

Once you define your main command, you can then run the modifier script:

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

modify_usage_error(cli)

除了使用错误之外,我没有探讨是否存在ClickException的运行时调用.如果存在,那么您可能需要修改自定义错误处理程序,以便在添加行click.exceptions.ClickException.show = show之前先检查ctx是属性,因为在初始化时似乎没有将ClickException馈入ctx.

I have not explored whether there are runtime invocations of ClickException other than usage errors. If there are, then you might need to modify your custom error handler to first check that ctx is an attribute before you add the line click.exceptions.ClickException.show = show since it does not appear that ClickException is fed ctx at initialization.

这篇关于Python Click:自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆