all Python 3sysfunction
sys.settrace()
debugging and tracing
Sets a trace function that is called on every function call, line, return and exception. pdb and coverage are built on it.
Syntax
sys.settrace(tracefunc) # tracefunc(frame, event, arg)
The global function receives only the 'call' event; 'line' events arrive only if it returns a local trace function (usually itself) — return None and that function's lines go untraced. It applies to the current thread and to new frames only, and the traced program runs many times slower. Turn it off with sys.settrace(None), ideally in finally. Since 3.12 sys.monitoring is a faster base for your own tools.
Examples
import sys
lines = []
def tracer(frame, event, arg):
if event == 'call' and frame.f_code.co_name != 'square':
return None
if event == 'line':
lines.append(frame.f_lineno - frame.f_code.co_firstlineno)
return tracer
def square(n):
r = n * n
return r
sys.settrace(tracer)
try:
square(3)
finally:
sys.settrace(None)
print(lines) # → [1, 2]
import sys
calls = []
def only_calls(frame, event, arg):
calls.append(frame.f_code.co_name)
return None
def f():
return 1
sys.settrace(only_calls)
try:
f()
f()
finally:
sys.settrace(None)
print(calls) # → ['f', 'f']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy