Previous Index Next

Debugging

Debugging is the process of detecting and removing of existing and potential errors in a software code that can cause it to behave unexpectedly or crash.

To debug a program, user has to start with a problem, isolate the source code of the problem, and then fix it. When the bug is fixed, then the software is ready to use.

Debugger

Debugging tools called debuggers are used to identify coding errors at various development stages. Programmers can trace the program execution step-by-step by evaluating the value of variables and stop the execution wherever required to get the value of variables or reset the program variables.

Pdb

Python has a built-in debugger called pdb. The easiest way to use pdb is to insert the following code in your program

import pdb
pdb.set_trace()

pdb.set_trace() insert a breakpoint to stop execution of program and return the control to the user. Look at the following example :

import pdb

temp = 1523
rev_no = 0

while temp > 0:
    digit = temp % 10
    rev_no = digit + rev_no * 10
    temp = temp // 10
    pdb.set_trace()
    
print("Reverse is ",rev_no) 

We have inserted the breakpoint pdb.set_trace() in above code, the program will stop execution at this point and return the control to the user. User can query the value of variables by giving pdb command at terminal as shown here:

> d:\example.py(6)()
-> while temp > 0:
(Pdb) p digit, temp, rev_no
(3, 152, 3)
(Pdb) c
> d:\example.py(6)()
-> while temp > 0:
(Pdb) p digit, temp, rev_no
(2, 15, 32)
(Pdb) c
> d:\example.py(6)()
-> while temp > 0:
(Pdb) p digit, temp, rev_no
(5, 1, 325)
(Pdb) c
> d:\example.py(6)()
-> while temp > 0:
(Pdb) p digit, temp, rev_no
(1, 0, 3251)
(Pdb) c
Reverse is  3251

Pdb Commands

In the above example we have used p command to display the value of variable and c command to continue the program. Here is a list of other pdb commands.

 

 l(ist)

 list 11 lines surrounding the current line

w(here)

display the file and line number of the current line

n(ext)

execute the current line s(tep) step into functions called at the current line

r(eturn)

execute until the current function’s return is encountered

 

Controlling Execution

b[#]

create a breakpoint at line [#] b list breakpoints and their indices

c(ontinue)

execute until a breakpoint is encountered

clear[#]

clear breakpoint of index [#]

 

Changing Variables / Interacting with Code

p

print value of the variable

!

execute the expression

run[args]

restart the debugger with sys.argv arguments [args]

q(uit)

exit the debugger

Previous Index Next