How to step through Python code to help debug issues

First step is to make the Python interpreter to enter into the debugging mode.
A. From the Command Line
Most straight forward way, running from command line, of python interpreter
$ python -m pdb scriptName.py > …/pdb_script.py(7)() -> “”” (Pdb)
B. Within the Interpreter
While developing early versions of modules and to experiment it more iteratively.
$ python Python 2.7 (r27:82508, Jul 3 2010, 21:12:11) on darwin Type “help”, “copyright”, “credits” or “license” for more information. >>> import pdb_script >>> import pdb >>> pdb.run(‘pdb_script.MyObj(5).go()’) > (1)() (Pdb)
C. From Within Your Program
For a big project and long-running module, can start the debugging from inside the program using import pdb and set_trace() like this :
!/usr/bin/env python # encoding: utf-8 # import pdb class MyObj(object): count = 5 def init(self): self.count= 9 def go(self): for i in range(self.count): pdb.set_trace() print i return if name == ‘main‘: MyObj(5).go()
Step-by-Step debugging to go into more internal
- Execute the next statement… with “n” (next)
- Repeating the last debugging command… with ENTER
- Quitting it all… with “q” (quit)
- Printing the value of variables… with “p” (print) a) p a
- Turning off the (Pdb) prompt… with “c” (continue)
- Seeing where you are… with “l” (list)
- Stepping into subroutines… with “s” (step into)
- Continuing… but just to the end of the current subroutine… with “r” (return)
- Assign a new value a) !b = “B”
- Set a breakpoint a) break linenumber b) break functionname c) break filename:linenumber
- Temporary breakpoint a) tbreak linenumber
- Conditional breakpoint a) break linenumber, condition
Note:**All these commands should be execute from **pdb
For in-depth knowledge, refer:-