Exercise 7.3

Objectives:

  • Learn how to run the Python debugger.

  • Learn how to run the Python profiler.

Files Created: None

Files Modified: None

(a) Using the Debugger

The debugger has the ability to run single Python functions using the pdb.runcall() function. Try using it to single-step through the execution of fileparse.parse().

>>> import fileparse
>>> import pdb
>>> pdb.runcall(fileparse.parse_csv, 'Data/portfolio.csv', types=[str,int,float])
> practical-python/fileparse.py(15)parse_csv()
-> if select and not has_headers:
(Pdb) s
> practical-python/fileparse.py(18)parse_csv()
-> f = open(filename)
(Pdb) s
... try single stepping by pressing 's' some more...
...

Experiment with some of the other debugger commands such as setting breakpoints, printing code listings, and inspecting values.

(b) Using the profiler

Run one of your earlier programs under the control of the Python profiler. For example:

% python -m cProfile report.py Data/portfolio.csv Data/prices.csv

Look at the output.

Note

To run the profiler in this manner, you have to launch Python from the command shell (e.g., a Unix terminal or the Windows command shell). Also, depending on how your report.py program works at this point, you might have to adjust the command line options accordingly.

Links