How to setup Emacs to use a given Python virtualenv?

Jeff picture Jeff · Jul 22, 2016 · Viewed 15.6k times · Source

I use Emacs for a number of tasks and as I am starting to work with Python I would like to keep using Emacs to code in Python.

I have set up a virtualenv for Python3, and it is working as desired. I also have Emacs 24.5 installed with the latest version of Emacs Prelude.

When I edit an Python source file all I expected is working -- code completion, object inspection, etc. -- but for my system wide Python installation, not for the virtual environment I have set up for the project.

How can I tell Emacs to use the virtual environment for a given project?

Answer

JCC picture JCC · Aug 26, 2016

Elpy has support for virtual environments built in via Pyvenv. Pyvenv can also be installed as a standalone package. Pyvenv added support for project-specific virtual environments in 2014, but I haven't experimented with them myself so I don't know how well it works.

If you want to code Python in Emacs, I would recommend installing Elpy. It really simplifies the process of getting a good environment up-and-running, and it is modular so you can deactivate sections over time when you decide you want a more tailored package.

You may also want to take a look at virtualenvwrapper.el, although Pyenv looks like it has more functionality. There's also auto-virtualenv, which attempts to automate the virtual environment discovery and activation.