首页 > 解决方案 > 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? 

标签: pythonpdb

解决方案


我曾经在这里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


推荐阅读