Skip to content

Python traceback format_exc

  • by

Python traceback format_exc is Print exception information and stack trace entries from traceback object. traceback.print_exc(limit=None, file=None, chain=True), This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).

Python traceback format_exc

Simple example code.

import traceback

try:
    a = 1 / 0
    
except:
    print(traceback.format_exc())

Output:

Python traceback format_exc

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

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)

Source: https://stackoverflow.com/questions/61139640/

Do comment if you have any doubts or suggestions on this Python Traceback topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading