Python的跟踪模块和文件路径 [英] Python's trace module and filepaths
问题描述
我正在使用 python的trace
模块来跟踪某些程序的执行代码.我注意到当以后打印执行时,它以以下形式打印(下面是最小的工作示例):
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>
有可能获得完整(绝对或相对)文件路径,而不仅仅是文件名.合理的是,在trace.Trace
调用中的某处应该有一个标志,应该允许我执行此操作,但是我似乎无法在文档中找到任何这样的参数.
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.
如果不存在这样的标志,我将如何获取文件路径?我想我可以检查sys.path
中的所有目录,但是当两个不同的目录具有相同名称的文件时,我该如何处理呢?
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?
推荐答案
不是很明显,但是我发现如果我在trace
中使用countfuncs
参数,或者在--listfuncs
参数中使用我从命令行使用trace
,我得到了完整的路径名.因此,对于程序:
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()
...(使用此处中的Doug Hellmann的示例),我得到以下输出:
... (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
这不是您想要的,因为您可以看到它正在忽略跟踪代码行的指令,因此它不会在这些代码行旁边提供文件路径.但是,它确实会告诉您Python脚本正在使用哪些文件.
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.
这篇关于Python的跟踪模块和文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!