FlowFX

Python virtual environments in Emacs

I am looking at Python again, specifically I am working through Brian Okken’s awesome book Python Testing with pytest. I did that the first time 9 years ago when I first learned Django and TDD, and even wrote a few blog posts about it.

Nowadays my development environment is Emacs, and very quickly I had to answer the question: how do I tell the really good emacs-python-pytest package where to find the virtual environment for my project. Luckily for me, Chris Siebenmann recently asked the same question on Mastodon and then blogged about it. That’s how I knew where to look.

It’s all about setting the environment variables PATH and VIRTUAL_ENV_PROMPT. My solution differs from Chris’s only in that I use the emacs-direnv package that’s already in my config, but I guess envrc works just as well.

(use-package direnv
  :hook
  (prog-mode . direnv-mode))

By checking what venv/bin/activate does to PATH and VIRTUAL_ENV_PROMT, I saw that they have to be set to /path/to/project/venv/bin:$PATH and venv respectively. A quick stack overflow search gave me a a one liner that returns the path directory of the file that it is run from. I put that into my `.envrc`, and now I can use this file in all my Python projects, and Emacs always knows how to run in the correct virtual environment.

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

export PATH=$SCRIPT_DIR/venv/bin:$PATH
export VIRTUAL_ENV_PROMT=venv

Off to more testing fun with pytest!