Skip to content
Advertisement

Python trace module – Trace lines as they are executed, but save to file, rather than stdout

I want to trace the lines of a python script as they are executed. However the programme I use needs to print things to stdout. The trace option to the python trace module prints them to stdout. Is there anwyay to tell it to not print them to stdout, but instead save them to a file? I tried setting the outfile parameter, but it doesn’t stop the printing of trace lines.

Advertisement

Answer

You could copy the trace module code, and make a few changes to get it to write its output to a file of your choosing. There are five print statements between lines 600 and 650 that are the ones you want to change. Since you don’t need to make it too pretty, you can add this to the very end of the file:

my_out_file = open("/home/mytrace.txt", "w")

and change the print statements so this:

print "%s(%d): %s" % (bname, lineno,
                      linecache.getline(filename, lineno)),

becomes this:

print >>my_out_file, "%s(%d): %s" % (bname, lineno,
                      linecache.getline(filename, lineno)),
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement