gpt4 book ai didi

python - 跟踪文件路径和行号

转载 作者:行者123 更新时间:2023-11-28 18:49:51 24 4
gpt4 key购买 nike

我正在使用 python 的 trace 模块来跟踪一些代码。当我以这种方式跟踪代码时,我可以获得以下两个结果之一:

调用:

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

结果:

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

调用 [ citation ]:

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)

结果:

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

我真正需要的是给我这个的跟踪:

<filepath> <line number>

我似乎可以使用上述信息并将它们交错以获得我需要的东西,但这种尝试在以下用例中会失败:

  • sys.path 包含目录 A 和目录 B
  • 有两个文件A/foo.pyB/foo.py
  • A/foo.pyB/foo.py 都包含函数 bar,定义在第 100 - 120 行
  • A/foo.pyB/foo.py 之间存在一些细微差别

在这种情况下,如果不静态分析每个 bar 中的代码,使用这种交错来正确识别调用了哪个 bar 是不可能的(如果我错了请纠正我) >,这本身对于非平凡的函数来说是非常困难的。

那么,我怎样才能得到我需要的正确跟踪输出呢?

最佳答案

用一点猴子补丁,这实际上很容易。仔细研究 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 方法来实现。

关于python - 跟踪文件路径和行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com