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.
SyntaxFollowing 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 valueThis method does not return any value.
Example 1Following 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 tracingOutput
Calling function: test_function Inside test functionExample 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 tracingOutput
Executing line 10 Line 1 Executing line 11 Line 2 Executing line 12 Line 3Example 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 tracingOutput
Before exception Exception: <class 'ValueError'> with value An error occurred
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4