Created
August 19, 2022 19:29
-
-
Save acbart/85554071c48ad3fa0377670a16d07171 to your computer and use it in GitHub Desktop.
Trace a program, determine when a class vs function is being entered
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import os | |
| import builtins | |
| build_class_orig = __build_class__ | |
| class Tracer: | |
| def __init__(self, code, filename): | |
| self.code = code | |
| self.filename = filename | |
| self.call_stack = ['<module>'] | |
| self.entering_class = None | |
| self.data = {} | |
| def begin(self): | |
| # Start capturing classes | |
| builtins.__build_class__ = self.build_class_hook | |
| # Compile and execute | |
| codeobj = compile(self.code, self.filename, 'exec') | |
| sys.settrace(self.tracer) | |
| exec(codeobj, self.data) | |
| sys.settrace(None) | |
| def end(self): | |
| builtins.__build_class__ = build_class_orig | |
| def build_class_hook(self, func, className, *baseClasses, **kw): | |
| print("Defining class:", className) | |
| self.entering_class = (func, className, baseClasses, kw) | |
| return build_class_orig(func, className, *baseClasses, **kw) | |
| def tracer(self, frame, event, args): | |
| if frame.f_back.f_code.co_filename != self.filename: | |
| return None | |
| if event == 'call': | |
| called_function = frame.f_code.co_name | |
| self.call_stack.append(called_function) | |
| print("We are entering a function:", called_function) | |
| if event == 'return': | |
| called_function = frame.f_code.co_name | |
| print("Returning from", called_function) | |
| return self.tracer | |
| def build(code: str, filename: str = "student.py"): | |
| tracer = Tracer(code, filename) | |
| tracer.begin() | |
| tracer.end() | |
| return tracer | |
| # python generate_tt.py <python_code.py> <versions> <blank_ratio> | |
| if __name__ == '__main__': | |
| # Get code file | |
| input_filename = sys.argv[1] | |
| filename_without_extension = os.path.splitext(os.path.basename(input_filename))[0] | |
| with open(input_filename) as input_file: | |
| input_contents = input_file.read() | |
| tracer = build(input_contents, input_filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment