Tom Insam

Automatically activating a Python virtualenv

I have a lot of different python projects in a lot of different directories, and like them all to have their own virtualenv. Because I can’t even be bothered to type a single line of code to activate them, I’ve ended up with this (slightly insane) setup:

Every project folder has a ./venv/ which is where I keep the virtualenv. Then, in my .bash_profile, I have the following snippet:

__activate_venv() {
  if [ -f ./venv/bin/activate ]
    . ./venv/bin/activate
    hash -r
    if (type deactivate >/dev/null 2>&1)
      hash -r
export PROMPT_COMMAND="__activate_venv"

In short - if the current directory has a venv/bin/activate script, then run it. Otherwise, if there’s something called deactivate that I can call, then do so.

So whenever I cd into a folder that has a ./venv/, it activates, and whenever I leave, it deactivates. This is probably insane.