Python Debugging Basics

Description

  • The following will just give some basic commands to use when needing to debug Continuity’s code. This likely isn’t overly useful for people using Eclipse’s debugger, but if you need to debug outside of Eclipse, this could be useful.

Using PDB

  • Python has a debugger: pdb, and it can be used to set break points, examine variables, evaluate expressions, etc.
  • One you have an area of Python code within Continuity that you would like to debug, you can set a break point by entering the following
import pdb;pdb.set_trace()
  • Once Continuity comes across that line, execution will stop and an interactive debugging session will start (in the Python shell in Continuity, or simply in the terminal window if you ran Continuity with the –no-shell option)
  • You can enter ‘help’ to show you the valid pdb commands.
  • You can enter ‘help command_name’ to get more help on a specific command.
  • Some of the most frequently used commands are:
    • where or w – That will show you the stack trace of all the methods that were executed prior to reaching the break point.
    • list or l – That will list the current few lines around where the break is. You can select to list more lines by specifying line numbers: l first_line_number, second_line_number
    • next or n – That will take you to the next line of code, and if that line is a function this will step OVER that function.
    • step or s – That will take you to the next line of code, and if it is a function this will step INTO that function.
    • continue or c – That will resume regular execution of the program allowing it to go to the next break point or simply run as normal.
  • If you want to see all the variables/methods that are currently in scope you can use some of the following:
    • dir(self) — assuming self has been defined where the pdb has stopped execution
    • locals().keys() — That will list all the local variables available.
    • globals().keys() — That will list all the global variables available.
  • You are able to use regular Python commands; however you should precede all Python commands with an exclamation point (!), which will differentiate the Python commands from pdb commands.
  • If you need to perform a multiple line Python code execution, e.g., if you want to test an if statement or a for loop, you can do the following:
(Pdb) !import code; code.interact(local=vars())
Python 2.5.1 (r251:54863, Nov 13 2007, 11:10:08) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
  • That will begin a normal Python session but with the variables already available for use.
  • Once done, you are supposed to be able to quit this interactive Python shell and return to pdb using ‘Ctrl-d’, however, I have not see that work, at least on a Mac using Python 2.5.