是否可以使用 colored-traceback.py 以彩色打印 `traceback.format_exc()`

Is it possible to print `traceback.format_exc()` in color using colored-traceback.py

我正在记录 traceback.format_exc() 的输出。是否可以使用它来着色 colored-traceback.py 在使用印刷品或替代品时?

示例代码:

import traceback
import colored_traceback
colored_traceback.add_hook(always=True)

a = 1 / 0 # prints colored traceback results 

try:
    a = 1 / 0
except:
    traceback.print_exc()  # prints in color white
    print(traceback.format_exc())  # prints in color white

colored_traceback looks useful, but I think it's overkill for your goal. You can achieve the desired effect with the pygments 库和几行代码:

import traceback

from pygments import formatters, highlight, lexers


try:
    a = 1 / 0
except:
    tb_text = "".join(traceback.format_exc())

    lexer = lexers.get_lexer_by_name("pytb", stripall=True)
    formatter = formatters.get_formatter_by_name("terminal256")
    tb_colored = highlight(tb_text, lexer, formatter)

    print(tb_colored)