SoFunction
Updated on 2025-04-20

Sharing tips for printing detailed stack information in Python

1. Use the traceback module

tracebackModules are tools specifically used in the Python standard library for handling exception stack traces. It provides a wealth of functions to obtain, format and print exception information.

1.1 traceback.print_exc()

When the program throws an exception,traceback.print_exc()Functions can print exception information and stack traces directly without manually processing exception objects. This method is simple and fast, suitable for fast positioning problems.

import traceback

try:
    # Your code logic    # Code that may throw exceptionsexcept Exception as e:
    traceback.print_exc()

1.2 traceback.format_exc()

If you need to further process the stack information, such as logging to a log file or custom output format,traceback.format_exc()It's a better choice. It returns a string containing stack information that you can print out or use for other purposes.

import traceback

try:
    # Your code logicexcept Exception:
    print(traceback.format_exc())

2. Print the stack in exception handling

existexceptIn the block, except for direct usetracebackIn addition to module functions, you can also combine themprintFunctions to print stack information. This method is more flexible and can customize the output content as needed.

2.1 Basic usage

import traceback

try:
    # Your code logicexcept Exception:
    print(traceback.format_exc())

2.2 Custom output

You can customize the output format as needed, such as adding additional error messages or highlighting certain key parts.

import traceback

try:
    # Your code logicexcept Exception:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print(f"Error: {exc_type.__name__}, Message: {exc_value}")
    print(traceback.format_exc())

3. Use the logging module

For large projects or scenarios where error information is required to be recorded in log files,loggingThe module provides more powerful log management functions.

3.1 Configuration log

First, you need to configure the log system, including log level, log file name, etc.

import logging
import traceback

(level=, filename='')

3.2 Record stack information

In exception handling, use()To record stack information. This method will automatically record the stack trace of the exception without manual formatting.

import logging
import traceback

try:
    # Your code logicexcept Exception:
    ("An unexpected error occurred")

IV. Advanced application of stack information

In addition to basic stack information printing, other tools and technologies can be combined to improve the efficiency of error tracking.

4.1 Integrated debugger

In some cases, printing the stack information directly may not be enough to resolve the problem. At this time, you can consider integrating the debugger, such aspdb, to execute the code step by step and observe the variable state.

import pdb; pdb.set_trace()

4.2 Performance Analysis

For performance issues, in addition to stack information, the execution time of the code is also required. AvailablecProfilemodule for performance analysis.

import cProfile

def my_function():
    # Your code logic    pass

('my_function()')

4.3 Code coverage

It is also important to understand the coverage of the code during testing. AvailablecoverageThe module analyzes the test coverage and ensures that all code paths are tested.

coverage run -m unittest discover
coverage report -m

This is the end of this article about sharing tips for printing detailed stack information in Python. For more information about printing detailed stack information in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!