Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTrace() in Python

Tags:

python

trace

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.

like image 782
Leonidas Avatar asked Oct 21 '09 13:10

Leonidas


2 Answers

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.

like image 185
Michael Dillon Avatar answered Oct 23 '22 00:10

Michael Dillon


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.

like image 29
nabucosound Avatar answered Oct 23 '22 00:10

nabucosound