all Python 3sysfunction
sys.setprofile()
debugging and tracing
Sets a profiling function called on entry to and exit from functions, built-ins included. cProfile was built on it before Python 3.12.
Syntax
sys.setprofile(profilefunc) # profilefunc(frame, event, arg)
Unlike settrace there are no line events, but calls into C are visible: 'c_call', 'c_return', 'c_exception', where arg is the built-in function itself. The return value is ignored. It affects the current thread: use threading.setprofile() for new threads and threading.setprofile_all_threads() (3.12) for all of them. Remember sys.setprofile(None) — that call itself also shows up in the log.
Examples
import sys
events = []
def prof(frame, event, arg):
if event in ('call', 'return'):
events.append((event, frame.f_code.co_name))
elif event == 'c_call':
events.append((event, arg.__name__))
def f():
return len('abc')
sys.setprofile(prof)
f()
sys.setprofile(None)
print(events)
# → [('call', 'f'), ('c_call', 'len'), ('return', 'f'), ('c_call', 'setprofile')]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy