Created
September 29, 2017 10:41
-
-
Save miguelvb/99abf5e104f0c4165bcd8dcdda89c386 to your computer and use it in GitHub Desktop.
tracer python
This file contains 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 inspect | |
class TracerClass(object): | |
def __init__(self): | |
self.whitespace = ' ' | |
self.indent_lvl = 0 | |
self.watched_dir = T_CONTROLLERS_DIR | |
def trace(self, frame, event, arg): | |
co = frame.f_code | |
fn_name = co.co_name | |
ws = self.whitespace | |
if fn_name == 'write': | |
return | |
line_no = frame.f_lineno | |
filename_full = co.co_filename | |
filename = path.basename(filename_full) | |
if self.watched_dir in filename_full: | |
if event == 'call': | |
self.indent_lvl += 1 | |
arg_names = inspect.getargs(frame.f_code).args | |
arg_dict = {name: frame.f_locals[name] for name in arg_names} | |
text = '' | |
for name, value in arg_dict.items(): | |
if isinstance(value, (str, tuple, unicode, list, int, float)) or name == 'callback': | |
text += "%s=%s, " % (name, value) | |
else: | |
text += "%s=%s, " % (name, value.__class__.__name__) | |
print('%s%s-call: ** %s ** (%s) in %s (%s)' % ( | |
self.indent_lvl*ws, self.indent_lvl, fn_name, text, filename, line_no) | |
) | |
return self.trace | |
elif event == 'return': | |
if isinstance(arg, (str, tuple, unicode, list, int, float)): | |
print('%s%s-return: ** %s ** => %s' % ( | |
self.indent_lvl*ws, self.indent_lvl, fn_name, arg) | |
) | |
else: | |
print('%s%s-return: ** %s ** => %s' % ( | |
self.indent_lvl*ws, self.indent_lvl, fn_name, arg.__class__.__name__) | |
) | |
self.indent_lvl -= 1 | |
TRACER = TracerClass() | |
def T(f): | |
def decorated(*args, **kwargs): | |
trace = sys.gettrace() | |
sys.settrace(TRACER.trace) | |
f(*args, **kwargs) | |
sys.settrace(trace) | |
return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment