Wednesday 29 January 2014

Pdb ftw

pdb - python debugger

If a script throws an exception, try running it in the debugger
python -m pdb
For example given the following (rubbish) python program
def naughty():
 raise Exception()

if we just run it the exception tries to escape ...
Traceback (most recent call last):
 File "", line 4, in <module>
 File "", line 2, in naughty
 raise Exception()

So, we know what line the problem's on. We could change the script to see what's going on using
import pdb; pdb.set_trace()
or we could run it under a debugger.

Run script through debugger

Invoke the pdb module in python and send it your script, e.g.
python -m pdb
This gives a (Pdb) prompt to type instructions in to:
> c:\dev\src\<module>()
-> def naughty():
Type 'c' for continue - it will halt when it gets an exception, as follows
(Pdb) c
Traceback (most recent call last):
 File "C:\Python27\lib\", line 1314, in main
 File "C:\Python27\lib\", line 1233, in _runscript
 File "C:\Python27\lib\", line 387, in run
 exec cmd in globals, locals
 File "<string>", line 1, in <module>
 File "", line 1, in <module>
 def naughty():
 File "", line 2, in naughty
 raise Exception()
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> c:\dev\src\
-> raise Exception()
At this point
 (Pdb) p <variable_name>
can be used to inspect variables, and
 (Pdb) a
shows any arguments to a function.

Main Pdb commands

Type 'q' for quit, 's' to step (maybe into another function) or 'n' to move on to the next line.
'w' shows where you are in the stack, 'u' moves up and 'd' moves down.
b(reak) [[filename:]lineno  sets a breakpoint.
There are more details in the manual:

No comments:

Post a Comment