Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional breakpoint using pdb

Tags:

python

pdb

Sounds like I'm missing something extremely simple, I'm trying to set a breakpoint in my python code using:

if(some condition):
        pdb.set_trace()

My error in the code comes after a large number of iterations..difficult to debug using print etc. I am able to print stuff when the condition hits but I would like to set brk-pt.

--EDIT--

Actual code:

import pdb
if (node_num == 16):
    print node_num
    pdb.set_trace()
like image 906
sanjay Avatar asked Aug 12 '14 22:08

sanjay


People also ask

What is pdb the Python debugger )?

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame.


1 Answers

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.

like image 151
mcchiz Avatar answered Oct 08 '22 12:10

mcchiz