Conditional breakpoint using pdb

It looks like I am missing something extremely simple, I am trying to set a breakpoint in my Python code using:

if(some condition):
        pdb.set_trace()

      

My error in code comes after a lot of iterations .. difficult to debug using print etc. I can print stuff when the state hits, but I would like to set brk-pt.

- EDIT -

Actual code:

import pdb
if (node_num == 16):
    print node_num
    pdb.set_trace()

      

+3


source to share


2 answers


I'm not sure why your code isn't working, but what you can do is on your local machine, create a new file for your minimal example to see if you can do what you want.

import pdb

for node_num in range(50):
    if node_num == 16:
        print(node_num)
        pdb.set_trace()

      

Now run it:

16
> /tmp/tmp.py(3)<module>()
-> for node_num in range(50):
(Pdb) p node_num
16

      



As you can see, it worked as intended with this trivial example, it's up to you how to adapt it to your code and / or figure out what else you did with your code / environment that prevented this prompt from showing.

Alternatively, if you have a function that dies in an exception and you want to know the exact string that called it, you should use instead post_mortem

. Wrap the problematic section of code with this

try:
    problem_function()
except Exception:  # or the specific exception type thrown
    pdb.post_mortem()
    raise

      

What post_mortem will do is to drop the breakpoint right where the exception happened (specifically on that stack) and this allows all values ​​to be checked and then allows execution to continue. However, I also put a boost at the end so that the exception continues as usual, and this is implied, since execution usually does not originate from where it dies, but simply pauses in that block of exception handling due to the call post_mortem

. Might just give up after checking what went wrong.

+1


source


I see you have found your solution, Sanjay. But for those who have arrived here looking for a means to set a conditional breakpoint using pdb, read on:

Instead of harsh coding conditions like if node_num == 16:

run pdb interactively. Sample code:

import pdb

for node_num in range(50):
  do_something(node_num)
...

      



In a shell, run the script in debug mode using -m pdb

:

[rick@rolled ~]$ python -m pdb abc.py
> /home/dcadm/abc.py(1)<module>()
-> import pdb
(Pdb) l
  1  -> import pdb
  2
  3     for node_num in range(50) :
  4       foo = 2**node_num
[EOF]
(Pdb) b 4, node_num > 4
Breakpoint 1 at /home/dcadm/abc.py:4
(Pdb) c
> /home/dcadm/abc.py(4)<module>()
-> foo = 2**node_num
(Pdb) node_num 
5
(Pdb)

      

The pdb shell command breaks at line 4 when node_num is greater than 4. b 4, node_num > 4

+8


source







All Articles