python - 如何将 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 命令期间创建的路径?
解决方案
您需要设置运行 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)
推荐阅读
- netlify - 如何在使用 Cecil 的 Netlify 上更改网站域名?
- sql - 包含多行的键上的火花合并(替换)
- php - 将部分分配给变量
- json - 不和谐重写如何让机器人在离开服务器时删除数据
- asp.net-core-webapi - Web api netcore 在 appsettings.json 文件中设置 Cors
- nginx - Nginx入口控制器路径重写不起作用
- c++11 - 在向量中查找继承的类对象 emplaced_back 的 unique_ptr
- java - 由于包名称不同,Firebase 中的用户身份验证失败?安卓、Java
- php - 使用 .htaccess 重写位于子目录中的网站的 url
- typescript - 安装@types/mysql2 的问题