Python sys.settrace() method
The Python sys.settrace() method that sets a global trace function which is used to monitor and control the execution of Python programs. The trace method is invoked at various points such as function calls, line executions, returns and exceptions.
It is primarily used for debugging and profiling by allowing developers to track the flow of execution and gather performance data. By setting a custom trace function one can collect detailed execution information, making it easier to diagnose issues or analyze program behavior.
Syntax
Following is the syntax and parameters of Python sys.settrace() method −
sys.settrace(tracefunc)
Parameter
This method accepts a function that takes three arguments such as frame, event and arg.
Return value
This method does not return any value.
Example 1
Following is the basic example sets a trace function that prints a message whenever a function is called. The sys.settrace(None) call at the end disables tracing −
import sys
def tracefunc(frame, event, arg):
if event == 'call':
print(f"Calling function: {frame.f_code.co_name}")
return tracefunc
def test_function():
print("Inside test function")
sys.settrace(tracefunc)
test_function()
sys.settrace(None) # Disable tracing
Output
Calling function: test_function Inside test function
Example 2
We can set up a trace function that prints a message each time a line of code is executed. In this example the trace function prints a message every time a line of code is executed within test_function −
import sys
def tracefunc(frame, event, arg):
if event == 'line':
lineno = frame.f_lineno
print(f"Executing line {lineno}")
return tracefunc
def test_function():
print("Line 1")
print("Line 2")
print("Line 3")
sys.settrace(tracefunc)
test_function()
sys.settrace(None) # Disable tracing
Output
Executing line 10 Line 1 Executing line 11 Line 2 Executing line 12 Line 3
Example 2
By setting up a trace method for exceptions that can print a message whenever an exception event is detected, we can gather detailed information about exceptions such as their type and value and below is the example −
import sys
def tracefunc(frame, event, arg):
if event == 'exception':
exc_type, exc_value, _ = arg
print(f"Exception: {exc_type} with value {exc_value}")
return tracefunc
def test_function():
print("Before exception")
raise ValueError("An error occurred")
print("After exception")
sys.settrace(tracefunc)
try:
test_function()
except ValueError:
pass
sys.settrace(None) # Disable tracing
Output
Before exception Exception: <class 'ValueError'> with value An error occurred