cpython_sandbox / Doc / library / trace.rst

:mod:`trace` --- Trace or track Python statement execution

Source code: :source:`Lib/`

The :mod:`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.

Command-Line Usage

The :mod:`trace` module can be invoked from the command line. It can be as simple as

python -m trace --count -C . ...

The above will execute :file:`` and generate annotated listings of all Python modules imported during the execution into the current directory.

Main options

At least one of the following options must be specified when invoking :mod:`trace`. The :option:`--listfuncs <-l>` option is mutually exclusive with the :option:`--trace <-t>` and :option:`--counts <-c>` options . When :option:`--listfuncs <-l>` is provided, neither :option:`--counts <-c>` nor :option:`--trace <-t>` are accepted, and vice versa.



These options may be repeated multiple times.

Programmatic Interface

Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed.

A container for coverage results, created by :meth:`Trace.results`. Should not be created directly by the user.

A simple example demonstrating the use of the programmatic interface:

import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],

# run the new command using the given tracer'main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")