问题
I am using python's trace module to trace the execution of some code. I notice that when the execution is later printed, it is printed in the following form (min working example follows below):
<filename>(<line number>): <line of code>
Is possible to get the full (either absolute or relative) file path instead of just the file name. It makes sense that there would be a flag somewhere in the call to trace.Trace
that should allow me to do this, but I don't seem to be able to find any such parameter in the docs.
If such a flag does not exist, how would I go about getting the file path? I guess I could check all the directories in sys.path
, but how would I then handle cases where two distinct directories have files with the same name?
回答1:
It wasn't very obvious, but I've found that if I use the countfuncs
parameter in trace
, or the --listfuncs
parameter if I'm using trace
from the command line, I get full path names. Thus, for the program:
import trace
from recurse import recurse
tracer = trace.Trace(count=False, trace=True, countfuncs=True)
tracer.run('recurse(2)')
tracer.results().write_results()
... (using Doug Hellmann's example from here) I get the following output:
functions called:
filename: <string>, modulename: <string>, funcname: <module>
filename: C:\Python33\lib\encodings\cp850.py, modulename: cp850, funcname: IncrementalEncoder.encode
filename: C:\Python33\lib\trace.py, modulename: trace, funcname: _unsettrace
filename: C:\usr\sjl\dev\test\python\recurse.py, modulename: recurse, funcname: recurse
This isn't quite what you were looking for because you can see it is ignoring the instruction to trace the lines of code, so it doesn't give the file path next to those lines of code. However, it does tell you exactly which files were being used by the Python script.
来源:https://stackoverflow.com/questions/14492837/pythons-trace-module-and-filepaths