Python pdb按条件设置断点

使用了一段时间pdb调试,但是都是一步一步调试,这次循环比较多,就有了按条件设置断点的需求了。pdb中按条件设置断点的方法有以下两种。

第一种是在pdb环境中设置:

andrew@ubuntu:~/PycharmProjects/Algotiths$ python find_kth_smallest.py
> /home/andrew/PycharmProjects/Algotiths/find_kth_smallest.py(23)<module>()
-> print("the {}th min num is {}".format(k,find_kth_smallest_num(l,k)))
(Pdb) s
--Call--
> /home/andrew/PycharmProjects/Algotiths/find_kth_smallest.py(3)find_kth_smallest_num()
-> def find_kth_smallest_num(l,k):
(Pdb) l
  1      
  2      
  3  ->    def find_kth_smallest_num(l,k):
  4          s=[]
  5          for i in range(k):
  6              res=float('inf')
  7              for item in l:
  8                  if res>item:
  9                      res,item=item,res
 10              if i!=k-1:
 11                  l.remove(res)
(Pdb) b 10,res==2  # 其中10 是断点设置的代码行,res==2是断点条件
Breakpoint 1 at /home/andrew/PycharmProjects/Algotiths/find_kth_smallest.py:10
(Pdb) b
Num Type         Disp Enb   Where
1   breakpoint   keep yes   at /home/andrew/PycharmProjects/Algotiths/find_kth_smallest.py:10
    stop only if res==2
(Pdb) c
> /home/andrew/PycharmProjects/Algotiths/find_kth_smallest.py(10)find_kth_smallest_num()
-> if i!=k-1:
(Pdb) p res
2

第二种是在代码中设置:

andrew@ubuntu:~/PycharmProjects/Algotiths$ python find_kth_smallest_pdb2.py
> /home/andrew/PycharmProjects/Algotiths/find_kth_smallest_pdb2.py(13)find_kth_smallest_num()
-> if i!=k-1:
(Pdb) p res
2
(Pdb) b
(Pdb) l
  8                  if res>item:
  9                      res,item=item,res
 10              if res==2:     # 断点条件
 11                  import pdb
 12                  pdb.set_trace()  
 13  ->            if i!=k-1:
 14                  l.remove(res)
 15              else:
 16                  return l[0]
 17      
 18      
(Pdb) 

 

参考:

pdb/ipdb for python break on editable condition

conditional breakpoint using pdb

posted @ 2018-03-16 20:19  谢世倾  阅读(2207)  评论(0编辑  收藏  举报