在终端上从Python着色异常 [英] Coloring exceptions from Python on a terminal
问题描述
有没有简单的方法来获取在命令行上着色的异常的消息?例如
def g():f()
def f():1/0
g ()
产生错误
跟踪(最近一次调用):
文件test.py,第3行,在< module>
g()
文件test.py,第1行,在g
中def g():f()
文件test.py,第2行,在f
def f():1/0
ZeroDivisionError:以零为整数除数或模数
我想整数除法或零除数在终端上着色或突出显示,以便我可以从长回溯(仅限Linux)中快速选择它。理想情况下,我不想为每个异常编写一个自定义类,而是以某种方式捕获和格式化所有类型。
编辑链接在注释中给出了如何使用外部软件解决问题的示例,但我对一个内部Python解决方案感兴趣。
您可以将自定义函数分配给 sys.excepthook
处理程序。
这个函数会被调用, import sys
pre>
def myexcepthook(type,value,tb):
import traceback
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments .formatters import TerminalFormatter
tbtext =''.join(traceback.format_exception(type,value,tb))
lexer = get_lexer_by_name(pytb,stripall = True)
formatter = TerminalFormatter()
sys.stderr.write(highlight(tbtext,lexer,formatter))
sys.excepthook = myexcepthook
此版本使用
pygments
库将跟踪文本转换为格式为ANSI颜色的文本,然后再将其写入stderr
。Is there an easy way to get the message of the exception to be colored on the command line? For example
def g(): f() def f(): 1/0 g()
Gives the error
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
I would like "integer division or modulo by zero" to be colored or highlighted on the terminal so that I can quickly pick it out of a long traceback (Linux only). Ideally, I wouldn't want to write a custom class for each Exception, but somehow catch and format all kinds.
EDIT: The question linked in the comments gives examples on how to solve the problem with external software, but I'm interested in an internal Python solution.
解决方案You can assign a custom function to the
sys.excepthook
handler. The function is called whenever there is a unhandled exception (so one that exits the interpreter).import sys def myexcepthook(type, value, tb): import traceback from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import TerminalFormatter tbtext = ''.join(traceback.format_exception(type, value, tb)) lexer = get_lexer_by_name("pytb", stripall=True) formatter = TerminalFormatter() sys.stderr.write(highlight(tbtext, lexer, formatter)) sys.excepthook = myexcepthook
This version uses the
pygments
library to convert the traceback text into one formatted with ANSI coloring, before writing it tostderr
.这篇关于在终端上从Python着色异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!