我用的是优秀的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/