Getting pdb in Emacs to use Python process from current virtualenv

python-shell uses variable python-default-interpreter to determine which python interpreter to use. When the value of this variable is cpython, the variables python-python-command and python-python-command-args are consulted to determine the interpreter and arguments to use. Those two variables are manipulated by virtualenv.el to set the current virtual environment.

So when you use python-shell command, it uses your virtual environments without any problem.

But, when you do M-! python, you're not using the variables python-python-command and python-python-command-args. So it uses the python tools it finds in your path.

When you call M-x pdb it uses gud-pdb-command-name as the default pdb tool. To redefine this variable, each time you activate an environment, you could do something like this :

(defadvice virtualenv-activate (after virtual-pdb)
  (custom-set-variables
     '(gud-pdb-command-name
        (concat virtualenv-active "/bin/pdb" ))))

(ad-activate 'virtualenv-activate)

To have pdb in your virtual environment, do the following :

cp /usr/bin/pdb /path/to/virtual/env/bin

Then edit the first line of /path/to/virtual/env/bin/pdb to have :

#! /usr/bin/env python

Reactivate your env and Pdb should now use your virtualenv python instead of the system-wide python.


Invoke pdb like this:

python -m pdb myscript.py

Instead of

pdb myscript.py