conditional breakpoint using pdb

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

Instead of hard coding conditions such as if node_num == 16:, run pdb in interactive mode. Sample code:

import pdb

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

In the shell start 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 b 4, node_num > 4 breaks at line 4 when node_num is greater than 4.


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

import pdb

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

Now running it:

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

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

Alternatively, if you have a function that is dying in an exception and you want to know the exact line that caused it, you should use post_mortem instead. 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 would do is dump a break point right at the point where the exception happened (specifically in that stack frame), and so this allows all values to be inspected and then let you continue execution. However I also put a raise at the end to allow the exception to continue as normal, and this is intended as execution doesn't normally from where it die but just pause at that exception handling block due to the post_mortem call. Might as well just give up after inspecting what went wrong.


To actually use conditional breakpoints in pdb, you can do the following:

b(reak) [([filename:]lineno | function) [, condition]]

https://docs.python.org/3/library/pdb.html#pdbcommand-break

Eg I'm running some test code that iterates over django views. I want to break only when the particular view I'm interested in is reached:

b C:\Users\powlo\project\tests\TestCase.py:350, view.view_name == 'app.views.export'

Tags:

Python

Pdb