Python 点击​​ : custom error message

标签 python command-line-arguments python-click

我用的是优秀的Python Click用于在我的工具中处理命令行选项的库。这是我的代码的简化版本(完整脚本 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 属性并在 main 函数中处理这个逻辑,但是对于这样一个小的添加感觉有点老套。

最佳答案

python-click 中大多数错误的消息构造由 UsageError 类的显示方法处理: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 是否是一个属性,因为它不会出现 ClickException在初始化时输入 ctx。

关于Python 点击​​ : custom error message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39596070/

相关文章:

Python:列表理解背后的机制

registry - 配置选项的优先级 : Environment, 注册表、配置文件和命令行的顺序是什么?

c - 在 C 中解析命令行参数

python - 深度Q-网络(DQN)学习游戏2048没有提高

python - x 轴标签未按正确顺序排序(matplotlib/pandas)

python - 如何从循环的 n 次迭代生成的 n 个字典列表中生成数据框?

python - 单击带有可选参数的工具

c - 我应该如何使用命令行参数从文件中填充整数数组?文件的大小和编号。元素的数量可能会有所不同

python - 在 click python 模块中的命令后获取参数

python - 隐藏使用中的值列表 - 单击