有没有一种简单的方法可以在命令行上为异常的消息着色?例如
def g(): f()
def f(): 1/0
g()
给出错误
Traceback (most recent call last):
File "test.py", line 3, in <module>
g()
File "test.py", line 1, in g
def g(): f()
File "test.py", line 2, in f
def f(): 1/0
ZeroDivisionError: integer division or modulo by zero
我希望在终端上对“整数除法或以零取模”进行着色或突出显示,以便我可以快速从长回溯中挑选出来(仅限 Linux)。理想情况下,我不想为每个异常编写自定义类,而是以某种方式捕获并格式化所有类型。
编辑:评论中链接的问题给出了如何使用外部软件解决问题的示例,但我对内部 Python 解决方案感兴趣。
最佳答案
您可以将自定义函数分配给 sys.excepthook
handler .只要出现未处理异常(即退出解释器的异常),就会调用该函数。
def set_highlighted_excepthook():
import sys, traceback
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
lexer = get_lexer_by_name("pytb" if sys.version_info.major < 3 else "py3tb")
formatter = TerminalFormatter()
def myexcepthook(type, value, tb):
tbtext = ''.join(traceback.format_exception(type, value, tb))
sys.stderr.write(highlight(tbtext, lexer, formatter))
sys.excepthook = myexcepthook
set_highlighted_excepthook()
此版本使用 pygments
library将追溯文本转换为具有 ANSI 着色格式的文本,然后再将其写入 stderr
。
有人把它变成了一个项目,可以检测终端支持并让您设置 pygments 样式,请参阅 colored-traceback.py
.
关于python - 终端上 Python 的着色异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14775916/