Search code examples
pythoncolorstraceback

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


I am logging output of traceback.format_exc(). Is it possible to color it using colored-traceback.py while using print or alternative?

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

Solution

  • colored_traceback looks useful, but I think it's overkill for your goal. You can achieve the desired effect with the pygments library and a few lines of code:

    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)