Python Glossary Русский

all Python 3threadingfunction

threading.settrace()

tracing and profiling

Sets a trace function for threads started after the call: each new thread passes it to sys.settrace() before run().

Syntax

threading.settrace(func)  # func(frame, event, arg) -> local tracer | None

Like setprofile(), it only affects new threads: the current and already running ones are not traced; use sys.settrace() for them or, since 3.12, settrace_all_threads(). The global function is called on the call event; to receive per-line line events it must return a local trace function (often itself), and returning None turns tracing off for that frame. pdb and coverage are built on this mechanism, and it slows code down a lot.

Examples

import threading
lines = []
def tracer(frame, event, arg):
    if frame.f_code.co_name != 'work':
        return None
    if event == 'line':
        lines.append(frame.f_lineno - frame.f_code.co_firstlineno)
    return tracer
def work():
    a = 1
    b = 2
threading.settrace(tracer)
t = threading.Thread(target=work)
t.start()
t.join()
threading.settrace(None)
work()  # главный поток не трассируется
print(lines)  # → [1, 2]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy