How to Step Through Python Code

How to Step Through Python Code thumbnail
The pdb debugger allows Python programmers to stop and step through their code.

Python includes as part of its libraries an interactive debugger called "pdb." This debugger, which a programmer can run within Python's Interactive Development Environment (IDE) lets a programmer perform common debugging tasks such as flagging errors, setting breakpoints and stepping through Python code. The debugger requires that the programmer use the debugger libraries in code.

  1. Including pdb Functionality in Code

    • The programmer includes python pdb statements in code. So, before anything, the programmer must include the pdb libraries.

      #!/usr/bin/python

      import pdb

      Now that the libraries are available in the program, the programmer can use the functions of the library to set debugging parameters and conditions throughout the code. In this way, a programmer will actually use the pdb debugger much like any other Python functionality: by importing it and calling its methods,

    Set a Break Point to Stop the Program

    • A "break point" is a position in the code where execution will pause. By setting a break point, the programmer can halt execution without stopping the actual program. This way, he can stop a running program before a suspected error point, and either check the conditions of the program, or step through the code to find where an error occurs. A break point begins where ever the programmer inserts the "pdb.set_trace()" method, as in this example

      a = 5

      b = a + b

      pdb.set_trace()

      c = 10 + a

      d = c + b

      a = d + a

      print a

    Stepping Through Code

    • Once the code hits the break point, execution will halt and the code will drop into the debugging mode. The terminal will display the next line of code executing, and then a prompt (PDB) waiting for instructions. At this point, the programmer can step line by line through the program using the "n" key. A sample output might look like:

      /usr/blah/prog.py(7)

      ->c = 10 + a

      (PDB)n

      /usr/blah/prog.py(8)

      ->d = c + b

    Print the Variables

    • This only shows the text on the code lines; however, a programmer might want to actually know what happens to those variables as the appear on the screen. He would then use the "p" command in the PDB debugger:

      (PDB) p a

      5

      (PDB)

      All the variables that exist in the current scope can be printed to the screen to check for value. This way, when the debugger steps through a line, the programmer can view changes in variable values.

Related Searches:

References

  • Photo Credit Jupiterimages/Photos.com/Getty Images

Comments

Related Ads

Featured