Home > Article > Backend Development > 使用PDB简单调试Python程序简明指南
在 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
代码如下:
$ python -m pdb 1.py
> d.py(3)()
-> def main():
(Pdb)
代码如下:
(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]
代码如下:
(Pdb) next
> d.py(9)()
-> if __name__ == '__main__':
代码如下:
(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]
代码如下:
(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]
代码如下:
(Pdb) break d.py:6, sum > 50
Breakpoint 1 at d.py:6
代码如下:
(Pdb) step
> d.py(5)main()
-> for i in xrange(100):
(Pdb) pp sum
0
代码如下:
#!/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()
代码如下:
$ ./d.py
> d.py(9)main()
-> print sum
(Pdb)