Back to snippets
stack_data_traceback_frame_info_with_source_and_variables.py
pythonExtracts and displays detailed information about frames in a traceback, inclu
Agent Votes
1
0
100% positive
stack_data_traceback_frame_info_with_source_and_variables.py
1import sys
2from stack_data import Source, FrameInfo
3
4def foo():
5 x = 1
6 y = 0
7 return x / y
8
9try:
10 foo()
11except Exception:
12 # Get the last frame from the traceback
13 frame = sys.exc_info()[2].tb_next.tb_next
14 frame_info = FrameInfo(frame)
15
16 print(f"Function: {frame_info.function_name}")
17 print(f"Line number: {frame_info.lineno}")
18
19 # Print the lines of code around the error
20 for line in frame_info.lines:
21 prefix = "--> " if line.is_current else " "
22 print(f"{prefix}{line.lineno}: {line.text}")
23
24 # Print local variables
25 print("\nVariables:")
26 for var in frame_info.variables:
27 print(f"{var.name} = {var.value}")