Route trace and line numbers

I am using a python module traceto track some code. When I spend the code this way, I can get one of the following two results:

Call

tracer = trace.Trace(count=False, trace=True, ignoredirs=[sys.prefix, sys.exec_prefix])
r = tracer.run('run()')
tracer.results().write_results(show_missing=True)

Result

<filename>(<line number>): <line of code>

Call [ quote ]:

tracer = trace.Trace(count=False, trace=True, ignoredirs=[sys.prefix, sys.exec_prefix], countfuncs=True)
r = tracer.run('run()')
tracer.results().write_results(show_missing=True)

Result

filename:<filepath>, modulename:<module name>, funcname: <function name>

I really need a trace that gives me the following:

<filepath> <line number>

It would seem that I could use the information above and alternate them to get what I need, but such an attempt will fail in the following use case:

  • sys.pathcontains a directory Aand a directory B.
  • There are two files A/foo.pyandB/foo.py
  • Both A/foo.py, and B/foo.pycontain the function bardefined in lines 100 - 120
  • There are slight differences between A/foo.pyandB/foo.py

, bar , (, , ), bar, - .

, , ?

+2
1

. trace, , . Trace.run, :

sys.settrace(globaltrace)   # Set the trace callback function
exec function               # Execute the function, invoking the callback as necessary
sys.settrace(None)          # Reset the trace

globaltrace Trace.__init__ . , , Trace.globaltrace_lt , Trace.localtrace_trace . Trace.localtrace, :

import trace
import sys
import time
import linecache

class Trace(trace.Trace):
    def localtrace_trace(self, frame, why, arg):
        if why == "line":
            # record the file name and line number of every trace
            filename = frame.f_code.co_filename
            lineno = frame.f_lineno

            if self.start_time:
                print '%.2f' % (time.time() - self.start_time),
            print "%s (%d): %s" % (filename, lineno,
                                  linecache.getline(filename, lineno)),
        return self.localtrace


tracer = Trace(count=False, trace=True, ignoredirs=[sys.prefix, sys.exec_prefix])
r = tracer.run('run()')

; Trace.run, - write_results. , , , tracer.results().write_results() . , , trace.CoverageResults.write_results .

+1

All Articles