1 min read

Python Trace Module

The trace module allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.

Importing the Module

import trace

Command Line Usage

The trace module can be invoked from the command line. It can be quite useful for debugging or understanding code flow without modifying the source.

Tracing Execution

To trace the execution of a script:

python -m trace --trace myscript.py

Coverage Analysis

To generate a coverage report (annotated listing of source files):

python -m trace --count --coverdir=. myscript.py

This will create a .cover file for each module imported and executed.

Programmatic Usage

You can also use the trace module within your Python code using the Trace class.

Creating a Tracer

import trace

# Create a Trace object
tracer = trace.Trace(
    count=False,
    trace=True,
    timing=True
)

# Run a command string
tracer.run('print("Hello World")')

Tracing Functions

You can trace specific functions using runfunc().

import trace

def recurse(level):
    print(f"Recurse level {level}")
    if level > 0:
        recurse(level - 1)

tracer = trace.Trace(trace=True)
tracer.runfunc(recurse, 2)

programming/python/python