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 ]
  then
    . ./venv/bin/activate
    hash -r
  else
    if (type deactivate >/dev/null 2>&1)
    then
      deactivate
      hash -r
    fi
  fi  
}
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.

Author: Tom Insam

programming / london / san francisco / bacon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s