Python Click:自定义错误消息
问题内容:
我在工具中使用了出色的Python
Click
库来处理命令行选项。这是我的代码的简化版本(此处为完整脚本):
@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".
很好,但是我很想告诉(新手)新用户,可以通过使用help标志获得更多帮助。换句话说,当命令无效时,请在错误消息中添加自定义语句,告诉人们尝试mytool --help
获取更多信息。
是否有捷径可寻?我知道我可以删除required
属性并在主函数中处理此逻辑,但是对于这样的次要添加来说,这有点不客气。
问题答案:
python-
click中大多数错误的消息构造是由UsageError类的show方法处理的:click.exceptions.UsageError.show
。
因此,如果您重新定义此方法,则可以创建自己的自定义错误消息。下面是一个自定义示例,该示例将帮助菜单附加到回答此SO问题的任何错误消息中:
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的运行时调用。如果存在,那么您可能需要修改自定义错误处理程序,以便在添加该行之前先检查ctx是属性,click.exceptions.ClickException.show = show
因为在初始化时似乎没有将ClickException馈入ctx。