Friday, March 23, 2012

Debugging and Profiling in Python

To debug hello.py, do
$ python -m pdb hello.py

You will immediately get the debug prompt, with the execution stopped before the first line of the program. You can now use:

l - to display source code around the line to be executed next
n - to execute the next line of code
s - to step into the next line of code
b <line no.> - to set breakpoints
b - to list breakpoints
clear <breakpt no.> - to clear breakpoints
c - to continue execution
tbreak <line no.> followed by c - to execute till a particular line
p <var> - to print contents of variables,
vars(obj) - to print contents of objects (same as obj.__dict__)
dir(obj) - to list attributes/methods of objects
help - to get more help.


 To profile hello.py, do
 $ python -m cProfile hello.py

The program will be run and you will get a profiler report on the console.

To debug a particular part of the code, do
import cProfile
profile = cProfile.Profile()
profile.enable()
# do something
profile.disable()
profile.dump_stats('something.prof')

To view the dump file, use cprofilev.

No comments:

Post a Comment