1 min read

Python Traceback Module

The traceback module provides a standard interface to extract, format and print stack traces of Python programs. It mimics the behavior of the Python interpreter when it prints a stack trace.

Importing the Module

import traceback

Printing Exceptions

traceback.print_exc()

This function prints exception information and stack trace entries from the traceback object to the file.

import traceback
import sys

try:
    1 / 0
except Exception:
    traceback.print_exc(file=sys.stdout)

Formatting Exceptions

traceback.format_exc()

This is like print_exc() but returns a string instead of printing to a file.

import traceback

try:
    1 / 0
except Exception:
    error_message = traceback.format_exc()
    print("Caught an exception:")
    print(error_message)

Extracting the Stack

traceback.print_stack()

This function prints a stack trace from its invocation point.

import traceback

def f():
    g()

def g():
    traceback.print_stack()

f()

programming/python/python