You can also debug a program in Python like Gcc/gdb, as long as the PDB module is introduced when you run the Python program (assuming that the program you are debugging is named d.py):
The 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
After running the above command, enter the following interface, you can enter GDB-like command to change the program execution process:
The code is as follows:
$ python-m pdb 1.py
> d.py (3) ()
def main ():
(PDB)
List shows the most recent code snippet for the program:
The code is as follows:
(PDB) List
1 #!/usr/bin/python
2
Def 3, 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:
The code is as follows:
(PDB) Next
> d.py (9) ()
if __name__ = = ' __main__ ':
Set a breakpoint on line 6th with break:
The 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__ ':
Ten main ()
[EOF]
If you want to set breakpoints at the function:
The 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__ ':
Ten main ()
[EOF]
You can also add conditions to breakpoints, such as setting conditions only when sum > 50 breaks:
The code is 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:
The code is as follows:
(Pdb) Step
> d.py (5) Main ()
-I in Xrange (100):
(PDB) pp sum
0
The PDB module can be used directly in the program, after the import PDB pdb.set_trace ():
The 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 ()
This allows the program to run as long as it is running./d.py can be run directly to print sum:
The code is as follows:
$./d.py
> d.py (9) Main ()
Print sum
(PDB)
Summary