Simple Switching of VirtualEnv Environments

If you're using Python for any kind of serious development virtualenv is highly recommended as a way to sandbox dependencies and allow you to run different libraries and or python versions for different projects. For more on Virtualenv and how to use it see VirutalEnv on PyPi

I wanted a quick way to switch virtual environments from anywhere. The result is a simple bash function that lists your available environments (albeit the assumption is you install your virtual environments in one place.) so you can choose one and activate it from anywhere.

The function should be placed in your .bashrc. The reason that this is a function and not a shell-script is that functions are executed in the current shell whereas placing the same code in a shell-script won't work as a shell script invokes a separate process. As the environment activation alters the environment it needs to be run in the current shell to work.

function venvswitch {
VENV_DIR=~/pythonenv
cd $VENV_DIR
echo 'Choose Virtual Env:'

select dir in *;
do
    if [ -n "$dir" ] && [ -f $dir/bin/activate ]
    then
      source $VENV_DIR/$dir/bin/activate
      break
    else
      echo "Error: You choice '$REPLY' does not correspond to a virtual env."
    fi
done
cd - > /dev/null
}

Basicaly what the script does is tell you what envs you have and you just select a number to activate that environment. Sourcing the bin/activate in the chosen environment alters your path and also adds a deactivation function.

To run it (after you've sourced your .bashrc - source ~/.bashrc) simpy type:

venvswitch

De-activating the virtalenv is as simple as running the following (this feature is provided by virtualenv itself):

deactivate

You will notice the prompt is returned to normal and your $PATH is reverted back to what it was prior to activation.

Alternatives

Here's some alternative VirutalEnv wrappers to try out:
Show Comments