You can also debug a program in Python like Gcc/gdb, by introducing a PDB module when you run a Python program (assuming that the program you want to debug is named d.py):
Copy Code code 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
After running the above command to enter the following interface, you can enter a command similar to GDB to change the execution process of the program:
Copy Code code as follows:
$ python-m pdb 1.py
> d.py (3) ()
-> def main ():
(PDB)
List displays the most recent code snippet for the program:
Copy Code code 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__ ':
Ten main ()
[EOF]
Next or N executes the next line of code:
Copy Code code as follows:
(PDB) Next
> d.py (9) ()
-> if __name__ = = ' __main__ ':
Use break to set a breakpoint on line 6th:
Copy Code code 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__ ':
Ten main ()
[EOF]
If you want to set a breakpoint at a function:
Copy Code code 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__ ':
Ten main ()
[EOF]
You can also add conditions to a breakpoint, such as setting a condition that only breaks when sum > 50:
Copy Code code as follows:
(Pdb) Break d.py:6, Sum > 50
Breakpoint 1 at D.py:6
If you want to see the value of a variable, you can print it with the PP command:
Copy Code code as follows:
(Pdb) Step
> d.py (5) Main ()
-> for I in Xrange (100):
(PDB) pp sum
0
You can use the PDB module directly in your program, after the import PDB pdb.set_trace ():
Copy Code code 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 ()
So just run the program./d.py can run directly to the print sum:
Copy Code code as follows:
$./d.py
> d.py (9) Main ()
-> Print sum
(PDB)
Summary