简体   繁体   English

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

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

I am logging output of traceback.format_exc() .我正在记录traceback.format_exc()的 output 。 Is it possible to color it using colored-traceback.py while using print or alternative?是否可以在使用 print 或替代方法时使用coloured-traceback.py对其进行着色?

Example code:示例代码:

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. colored_traceback看起来很有用,但我认为这对你的目标来说太过分了。 You can achieve the desired effect with the pygments library and a few lines of code:使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM