Tracing the execution of scripts?

Stephan Kuhagen nospam at domain.tld
Fri Oct 27 01:10:21 EDT 2006


"Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote:

> Basically, is there something that will log every line of Python code
> executed, in its order of execution, to a text file so that I can see
> what is (or isn't) happening that I am expecting?

Python itself can do this for you. A __VERY__ simple approach:

|def myCallTrace (frame, event, arg):
|  tracefile.write('localTrace\n  frame: '+str(frame)+'\n  event:
|'+str(event)+'\n  arg: '+str(arg)+'\n')
|  tracefile.write('    '+str(inspect.getframeinfo(frame))+'\n')
|
|def myTrace (frame, event, arg):
|  tracefile.write('globalTrace\n  frame: '+str(frame)+'\n  event:
|'+str(event)+'\n  arg: '+str(arg)+'\n')
|  if event == 'call':
|    return myCallTrace
|
|import inspect
|import sys
|
|sys.settrace(myTrace)
|tracefile = file('trace.txt', 'w')

Insert this in you program and you get a trace of every line of Python-Code
executed in the file trace.txt. You must read the documentation of the
module inspect and of sys.settrace() to understand, what happens and what
it means. Additionally, if it should work with threads, you must take care
that every thread gets its own output file. But as a first step to get a
trace of execution, this should do it.

HTH, Regards
Stephan




More information about the Python-list mailing list