首页 > 解决方案 > 如何将 self 对象传递给 trace.Trace.run() 方法?

问题描述

为了跟踪程序的执行(确切地说,我想跟踪执行代码中特定行时使用的模块/类/方法),我尝试使用跟踪模块

我想探索的路线是这样的:

trait = self._trait(name, 0)

所以我将代码中的这一行更改为:

#trait = self._trait(name, 0) import trace tracer = trace.trace(count=False, trace=True) tracer.run('trait = self._trait(name, 0)')

问题是在这种情况下会引发异常,因为 self 没有定义(因为我们在 tracer.run() ! 方法中传递了一个字符串)。

File "/usr/lib64/python3.6/trace.py", line 462, in runctx exec(cmd, globals, locals) File "<string>", line 1, in <module> NameError: name "self' is not defined

是否可以将对象(作为 self)传递给 tracer.trace.run() 方法?

是否有另一种更适合这种情况的方法来探索在 python 命令期间创建的路径?

标签: pythontrace

解决方案


您需要设置运行 python 语句的上下文以使用该runctx方法进行跟踪。这是一个示例,它表示将self跟踪器上下文作为局部变量放入,以便可以在那里引用它:

import trace

class A:
  def f(self):
      self.g()
      print('f')

  def g(self):
      print('g')

  def h(self):
      # trace self.f()
      tracer = trace.Trace(count=False, trace=True)
      # define a local variable in the context named 'self'
      tracer.runctx('self.f()', locals={'self': self})

a = A()
a.h()

输出:

 --- modulename: trc, funcname: f
trc.py(5):       self.g()
 --- modulename: trc, funcname: g
trc.py(9):       print('g')
g
trc.py(6):       print('f')
f
 --- modulename: trace, funcname: _unsettrace
trace.py(77):         sys.settrace(None)

推荐阅读