从另一个脚本跟踪Python脚本的执行

2024-05-15 22:31:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个分析Python代码的教育工具,目前,我需要一种在代码执行期间访问变量值的方法

我知道我可以使用Python模块trace,我从python -m trace example.py得到的输出是我可以用来完成我想要的任务的理想数据,但是我无法让它以编程方式运行,通过脚本的命令行运行它是我最后的资源

another question中,作者想做与我几乎相同的事情,加上this question通过使用^{}为我指出了正确的方向

在下面的代码示例中,我能够以我想要的方式跟踪代码执行

import StringIO
import sys

# to programmatically provide stdin values to the script
sys.stdin = StringIO.StringIO("3")

# to output current variable values
def dump_frame(frame, event, arg):
  print '%d: %s' % (frame.f_lineno, event)
  for k, v in frame.f_locals.iteritems():
      print '    %s = %r' % (k, v)
  return dump_frame

# external script should be executed here, instead
# of this static program
def main():
  j = int(raw_input())

  while j < 10:
    j += 1

  print j

sys.settrace(dump_frame)

main()

但是我需要动态加载main()中的代码,我该怎么做呢?我尝试了下面所示的操作,其中“mycode”来自“./mycode.py”,它包含了上面代码中main()的脚本。但是,跟踪输出变得太长,可能是因为__import__函数的内部工作也被跟踪了

# ...
def main():
  __import__('mycode')
# ...

那么,如何动态加载代码并跟踪它,以获得变量值呢


Tags: to代码pyimportmaindefsys方式