Simple Guide for using PDB to debug Python programs, and a simple guide for using pdb to debug python
In Python, you can also debug programs like gcc/gdb, as long as you introduce the pdb module when running the Python Program (assuming the program to be debugged is named d. py ):
Copy codeThe Code is as follows:
$ 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
Run the preceding command and enter the following interface. You can enter a command similar to gdb to change the execution process of the program:
Copy codeThe Code is as follows:
$ Python-m pdb 1.py
> D. py (3 )()
-> Def main ():
(Pdb)
List shows the latest code segment of the program:
Copy codeThe Code is as follows:
(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]
Run next or n:
Copy codeThe Code is as follows:
(Pdb) next
> D. py (9 )()
-> If _ name _ = '_ main __':
Use break to set a breakpoint on Line 1:
Copy codeThe Code is as follows:
(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]
If you want to set a breakpoint in a function:
Copy codeThe Code is as follows:
(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]
You can also add conditions to the breakpoint. For example, you can set the condition to break only when sum> 50:
Copy codeThe Code is as follows:
(Pdb) break d. py: 6, sum> 50
Breakpoint 1 at d. py: 6
To view the value of a variable, use the pp command to print it out:
Copy codeThe Code is as follows:
(Pdb) step
> D. py (5) main ()
-> For I in xrange (100 ):
(Pdb) pp sum
0
You can directly use the pdb module in the program. After importing pdb, pdb. set_trace ():
Copy codeThe Code is as follows:
#! /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 ()
In this way, you can run the program./d. py directly to print sum:
Copy codeThe Code is as follows:
$./D. py
> D. py (9) main ()
-> Print sum
(Pdb)
Summary