tags:

views:

116

answers:

2

Is there a way to use the setTrace() function in a script that has no method definitions? i.e.

for i in range(1, 100):
    print i

def traceit(frame, event, arg):
    if event == "line":
        lineno = frame.f_lineno
        print "line", lineno

return traceit

sys.settrace(traceit)

so ideally I would want the trace function to be called upon every iteration / line of code executed in the loop. I've done this with scripts that have had method definitions before, but am not sure how to get it to work in this instance.

+1  A: 

settrace() is really only intended for implementing debuggers. If you are using it to debug this program, you may be better off using PDB

According to the documentation, settrace() will not do what you want.

If you really want to do this line by line tracing, have a look at the compiler package which allows you to access and modify the AST Abstract Syntax Tree produced by the Python compiler. You should be able to use that to insert calls to a function which tracks the execution.

Michael Dillon
+1  A: 

I only use one simple syntax line to rule them all:

import pdb; pdb.set_trace()

Put it wherever you want to break execution and start debugging. Use pdb commands (n for next, l for list, etc).

Cheers,

H.

nabucosound