Tuesday, March 15, 2011

[Level 3] How to debug python in run-time environment.

You can use pdb module to debug your python program in run-time environment in two ways.
1. import pdb module and set trace.
#!/bin/env python
import os, sys
import pdb; pdb.set_trace()
2. use python command and import pdb module.
$ python -m pdb ./myapp.py

And about pdb useful commands:
l: list source code
b: break point
r: run
s: step: into function
n: next: run next line
c: : continue next loop
where: where is the break point now
? help

$ python -m pdb ./myapp.py
(Pdb) l
  1   #!/bin/env python
  2  -> import os, sys
  3   #print os.environ['PATH']
  4   os.environ['PATH']='/usr/bin:'+os.environ['PATH']
  5   #if './' not in sys.path: sys.path.append('./') 
  6   #if './lib' not in sys.path: sys.path.append('./lib')
  7   #if '../lib' not in sys.path: sys.path.append('../lib')
  8   exec_file = sys.argv[0]
  9   os.chdir(os.path.dirname(sys.argv[0]))
 10   run_at_dir = os.getcwd()
 11   os.chdir('../lib')
(Pdb) b 4
Breakpoint 1 at /opt/ruckuswireless/wsg/cli/bin/setup.py:4
(Pdb) b 8
Breakpoint 2 at /opt/ruckuswireless/wsg/cli/bin/setup.py:8
(Pdb) c
> /opt/ruckuswireless/wsg/cli/bin/setup.py(4)()
-> os.environ['PATH']='/usr/bin:'+os.environ['PATH']
Wish this helps. regards, Stanley Huang