Trace Function not working as intended with imported files

Viewed 53

I'm currently working on a program that displays variables line by line as code executes from a file (think trace tables). I'm able to get it working fine when the code is encased within a function inside the program itself but when I import the same code, it tracks new variables that I don't want to track (as they don't appear in the actual script). Is there any way I can isolate the variables specific to the program? (it'll also be useful for when I'm ignoring variables from pulled libraries in Python).

Here's my program so far:

import sys
import dis 
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog

line_record = [] #where data on variables will be stored line by line
def trace(frame, event, arg_unused): #tracing function
    global line_record
    relevant_locals = {}
    temp_vars = frame.f_locals.copy()
    for k,v in temp_vars.items():
          if not k.startswith("__"):
              relevant_locals[k] = v
    line_record.append([frame.f_lineno, relevant_locals])
    return trace

def print_results(v_list):
    print_record="" #variable which holds the formatting of the data
    for item in v_list: #iterating for data in each recorded line
        print_record += "Line " + str(item[0]) + "= "
        if item[1]=={}: #catching lines with no variables
            print_record += "no variables"
        else:
            for key in item[1]: #iterating through each variable to fetch associated data
                print_record += str(key)+"="+str(item[1].get(key,"error"))+"|"
        print_record += "\n"
    return print_record


root = Tk() #creating the main window
root.title("frame")
root.iconbitmap("c:/Users/hamza/Documents/Other/Python/GUI/6 images/apple.ico")

root.filename = filedialog.askopenfilename(initialdir="/", title="select file",filetypes=[("python files","*.py")]) #import python files through tkinter dialog box
user_code = compile(open(root.filename, "rb").read(), root.filename, 'exec') #compiling imported code in order to use later in project

sys.settrace(trace)
exec(user_code)
sys.settrace(None)
print(print_results(line_record))

root.mainloop()

And for reference (if needed), my test code is:

a = 1
b = 2

a = a + b

If you need any more information please don't hesitate to ask, I'm happy to clarify, thanks.

0 Answers
Related