在 Python 中也可以像 gcc/gdb 那样调试程序,只要在运行 Python 程序时引入 pdb 模块(假设要调试的程序名为 d.py):
$ vi d.py
#!/usr/bin/python
def main():
i, sum = 1, 0
for i in xrange(100):
sum = sum + i
print sum
if __name__ == '__main__':
main()
$ python -m pdb d.py
#!/usr/bin/python
def main():
i, sum = 1, 0
for i in xrange(100):
sum = sum + i
print sum
if __name__ == '__main__':
main()
$ python -m pdb d.py
运行上面的命令后进入以下界面,可以输入类似 gdb 的命令来改变程序的执行流程:
$ python -m pdb 1.py
> d.py(3)()
-> def main():
(Pdb)
> d.py(3)()
-> def main():
(Pdb)
list 显示程序的最近代码段:
(Pdb) list
1 #!/usr/bin/python
2
3 -> def main():
4 i, sum = 1, 0
5 for i in xrange(100):
6 sum = sum + i
7 print sum
8
9 if __name__ == '__main__':
10 main()
[EOF]
next 或者 n 执行下一行代码:
(Pdb) next
> d.py(9)()
-> if __name__ == '__main__':
用 break 在第6行设置一个断点:
(Pdb) break d.py:6
Breakpoint 1 at d.py:6
(Pdb) list
1 #!/usr/bin/python
2
3 def main():
4 i, sum = 1, 0
5 -> for i in xrange(100):
6 B sum = sum + i
7 print sum
8
9 if __name__ == '__main__':
10 main()
[EOF]
Breakpoint 1 at d.py:6
(Pdb) list
1 #!/usr/bin/python
2
3 def main():
4 i, sum = 1, 0
5 -> for i in xrange(100):
6 B sum = sum + i
7 print sum
8
9 if __name__ == '__main__':
10 main()
[EOF]
如果想在函数处设置断点:
(Pdb) break d.main
d.py:3
(Pdb) list
1 #!/usr/bin/python
2
3 B def main():
4 -> i, sum = 1, 0
5 for i in xrange(100):
6 sum = sum + i
7 print sum
8
9 if __name__ == '__main__':
10 main()
[EOF]
d.py:3
(Pdb) list
1 #!/usr/bin/python
2
3 B def main():
4 -> i, sum = 1, 0
5 for i in xrange(100):
6 sum = sum + i
7 print sum
8
9 if __name__ == '__main__':
10 main()
[EOF]
还可以给断点加条件,比如设置条件只有当 sum > 50 的时候才 break:
(Pdb) break d.py:6, sum > 50
Breakpoint 1 at d.py:6
Breakpoint 1 at d.py:6
如果想查看某个变量的值,可以用 pp 命令打印出来:
(Pdb) step
> d.py(5)main()
-> for i in xrange(100):
(Pdb) pp sum
0
> d.py(5)main()
-> for i in xrange(100):
(Pdb) pp sum
0
可以直接在程序里使用 pdb 模块,import pdb 后 pdb.set_trace():
#!/usr/bin/python
import pdb
def main():
i, sum = 1, 0
for i in xrange(100):
sum = sum + i
pdb.set_trace()
print sum
if __name__ == '__main__':
main()
import pdb
def main():
i, sum = 1, 0
for i in xrange(100):
sum = sum + i
pdb.set_trace()
print sum
if __name__ == '__main__':
main()
这样只要运行程序 ./d.py 就可以直接运行到 print sum 处:
$ ./d.py
> d.py(9)main()
-> print sum
(Pdb)
> d.py(9)main()
-> print sum
(Pdb)
总结