Python comes with its own debugger module — pdb. You can set breakpoints, step through your code, inspect stack frames and more.
How to Start the Debugger
Import pdb
and insert pdb.set_trace()
into your code.
pass
A Very Simple Test File
'''
debug_test.py
'''
def doubler(a):
result = a * 2
print( result )
return result
def main():
for i in range( 1, 10 ):
doubler(i)
if __name__ == "__main__":
main()
Import the debugger in IDLE and have it run your module.
When you enter continue, the debugger will continue execution until it reaches a breakpoint or the script ends.
>>> import debug_test
>>> import pdb
>>> pdb.run('debug_test.main()')
> <string>(1)<module>()
(Pdb) continue # type `continue` or `c` to go ahead and run the script
2
4
6
8
10
12
14
16
18
Call the debugger on the command line.
python -m pdb debug_test.py
You will note that the debugger restarts at the end. This preserves the debugger’s state(such as breakpoints) and can be more useful than having the debugger stop.
Stepping Through the Code
next(or n)
is equivalent tostep
in visual studio.step(or s)
is equivalent tostep into
in visual studio.args(or a)
print the current argument list to the screen.jump(or j)
followed by a space and a line number you want to ‘jump’ to.
Setting Breakpoints
break(or b)
follows a space and a line number you want to break on. You can also prefix the line number with a file name and colon to specify a breakpoint in a different file. This command also allows you to set a breakpoint with thefunction
argument.tbreak
command will set a temporary breakpoint which is automatically removed when it gets hit.