import sys import io def execute_with_breakpoints(filename): """ Reads and executes a Python program, pausing at '#breakpoint' as breakpoints to print executed lines and variable changes. """ with open(filename, 'r') as f: lines = f.readlines() global_vars = {} local_vars = {} current_block = [] exec("pass", global_vars, local_vars) last_breakpoint_vars = {**global_vars, **local_vars} temp_module_code = '' print("Start execution...\n") for i, line in enumerate(lines): current_block.append(f" [{i+1}] {line.rstrip()}") # Create a temporary module to execute each line # This allows capturing local variables more effectively temp_module_code += line if '#break' in line or i+1 == len(lines): try: # Capture print output old_stdout = sys.stdout redirected_output = io.StringIO() sys.stdout = redirected_output # Execute the code in a new scope to isolate variables exec(temp_module_code, global_vars, local_vars) sys.stdout = old_stdout # Restore stdout except Exception as e: print(f"Error executing: {e}") sys.stdout = old_stdout break finally: pass # sys.stdout = old_stdout # Restore stdout # print current block of statements: print("<>:") for l in current_block: print(l) # print output of the execution of these statements. output_string = redirected_output.getvalue() if output_string: print("<>:") print(output_string) # print break point information about variable changes. print("-------- breakpoint reached or end of program -------") current_vars = {**global_vars, **local_vars} print("-- Variable Changes since last breakpoint:") has_changes = False for var_name, var_value in current_vars.items(): if var_name not in last_breakpoint_vars or last_breakpoint_vars[var_name] != var_value: print(f"-- {var_name}: {last_breakpoint_vars.get(var_name, '')} -> {var_value}") has_changes = True if not has_changes: print("-- no variable has changed value.") last_breakpoint_vars = current_vars.copy() if i+1 == len(lines): print("------------ Program Execution Finished -------------\n") else: print("-----------------------------------------------------\n") # initialize for the next breakpoint. current_block = [] temp_module_code = '' # Example usage: if __name__ == "__main__": if len(sys.argv) > 1: execute_with_breakpoints(sys.argv[1]) else: # Create a dummy Python file for testing with open("my_test.py", "w") as f: f.write( # Create a file named 'my_program.py' with some Python code and '#state' comments """# my_test.py x = 10 y = 20 print(f"value of x: {x}") print(f"value of y: {y}") #state x = x - 5 z = x + y #state z += 1 print(f"Final value of z: {z}") """) execute_with_breakpoints("my_test.py")