python - Adding breakpoints programmatically using pdb in python
问题描述
I find that in large multi-tier pieces of software it is typically easier to debug python code by putting the following within the code.
import pdb; pdb.set_trace()
this sets a breakpoint at the LOC where I put the statement, and I can continue within the code using pdb in an interactive way and inspect the code execution etc.
I would like to know if its possible to add more than one breakpoints for such python debugging such that I can do c
in the interactive python debugger and hit the next breakpoint?
i.e. for instance
<python code>
import pdb; pdb.set_trace();
... interactive debugging....
...press c here....
<more python code>
...
....
<breakpoint>// How can we insert such a breakpoint?
解决方案
我曾经在这里ipdb
通过大量修改它来做到这一点。然而,我最近重新发明了轮子,以一种我认为更简单的方式可以与任何 Bdb 调试器一起使用。测试pdb
和和ipdb
#!/usr/bin/env python3
import pdb
import sys
import ipdb.__main__
def foo(x):
return x+1
class RunningTrace():
def set_running_trace(self):
frame = sys._getframe().f_back
self.botframe = None
self.setup(frame, None)
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_continue()
self.quitting = False
sys.settrace(self.trace_dispatch)
class ProgrammaticPdb(pdb.Pdb, RunningTrace):
pass
class ProgrammaticIpdb(ipdb.__main__.debugger_cls, RunningTrace):
pass
p = ProgrammaticPdb()
# p = ProgrammaticIpdb(ipdb.__main__.def_colors)
p.onecmd('b bar.py:38') # Works before set_running_trace
p.set_running_trace()
p.onecmd('b foo') # only works after calling set_running_trace
p.onecmd('l')
x=-1
x=2
x=0
x=foo(x)
print(x)
您可以在调用之前通过文件/行号set_running_trace
设置断点,但是您只能在调用之后设置取决于范围的断点set_running_trace
,例如本例中的函数名称foo
。
推荐阅读
- typescript - 索引对象的打字稿参考值
- laravel - 如何使用实时服务器中的干预在 laravel 中创建缩略图?
- node.js - 如何使用 nodejs 创建具有特定域的 api 端点或 api?
- kubernetes - Kubernetes Pod 一次性初始任务
- vba - 如何仅替换字符串中的某些空格?
- omnet++ - 如何从 omnet++ 中的 c++ 代码访问运行时 queueLength 参数?
- sql - 将长 SQL 代码放入 VBA Excel 的最简单方法是什么?
- java - 如何从 Mockito Junit 正确调用超类方法
- c# - 是否有可能知道在 IEnumerable 上调用了哪些操作?
- android - 如何在 Android 项目中为单元测试提供自定义应用程序类