Tracking project virtual environments with pyvenv-tracking-mode
Apr 9, 2018

First of all, you need to install pyvenv-mode. This package is a dependency of elpy and is installed when you execute

(package-install 'elpy)


Elpy is a great mode for editing Python, and I would strongly recommend using it.

To set up pyvenv-tracking-mode, add the following to your init file (you should have use-package installed):

(use-package pyvenv
:ensure t
:init
(setenv "WORKON_HOME" "~/miniconda3/envs/")
(pyvenv-mode 1)
(pyvenv-tracking-mode 1))


The WORKON_HOME variable should be set to the conda directory containing your environments. This use-package declaration enables pyvenv-mode and pyvenv-tracking-mode.

Now, when you are in a project buffer, execute add-dir-local-variable. It will first prompt for the mode (in which the local variable will be set), then which variable to set, and finally the value of the variable. The mode should obviously be python, the variable you should set is pyvenv-workon, and the value is a string value "my-conda-environment". Note that the quotes are important, because the variable can only be set to a string value.

Emacs will look for .dir-locals.el file in all parent directories of the current file, so it is possible to put the .dir-locals.el file in the project root directory.

If you reload the project buffer (M-x revert-buffer), the environment will automatically change. Moreover, whenever you switch to this buffer in the future, the environment will be set correctly.