All,
I have a question similar to question 2617120, found here:
where the questioner wanted pointers on how to make python printout function parameters when they were executed via a tracing hook.
I'm looking for something very similar to this but with a twist. Instead of all data being dumped out, I want to eval the code when its running, and to print out any evaled variables. For example, with the following code:
for modname in modnames:
if not modname or '.' in modname:
continue
...
the trace hook would cause the following to be printed out:
for modname in modnames: | for init in init,., encoding
|
if not modname or '.' in modname: | if not init or '.' in init
continue | continue
if not modname or '.' in modname: | if not . or '.' in .
... |
where the line of code undergoes interpolation based off of the running frame. I've done this in perl where it's a lifesaver in certain circumstances.
Anybody have ideas on the best way of going about doing this in python? I have my ideas, but I'd like to hear what people think (and if they have any already pre-made solutions)
Here, btw is the reference code:
import sys
import linecache
import random
def traceit(frame, event, arg):
if event == "line":
lineno = frame.f_lineno
filename = frame.f_globals["__file__"]
if filename == "<stdin>":
filename = "traceit.py"
if (filename.endswith(".pyc") or
filename.endswith(".pyo")):
filename = filename[:-1]
name = frame.f_globals["__name__"]
line = linecache.getline(filename, lineno)
print "%s:%s:%s: %s" % (name, lineno,frame.f_code.co_name,line.rstrip())
return traceit
def main():
print "In main"
for i in range(5):
print i, random.randrange(0, 10)
print "Done."
sys.settrace(traceit)
main()