Switching between virtualenvs with tab completion

EDIT 17 April 2015: I originally wrote this post a month or two before I found out about virtualenvwrapper. The original content follows, but I strongly recommend using virtualenvwrapper to manage your virtualenvs :-)

Often I find myself working on (or maintaining) multiple python projects that require different virtual environments. The need to switch between them arises frequently enough that I thought it would be nice to create a shortcut for doing so. That’s how I wound up with this in my .bashrc:

ENVSDIR="/home/me/PROJECTS/envs"
function switchenv {
    deactivate 2> /dev/null
    source "${ENVSDIR}/${1}/bin/activate"
}
_switchenv() {
    local cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=( $(compgen -W "`ls -1 ${ENVSDIR}`" -- $cur) )
}
complete -F _switchenv switchenv

Basically, all of my environments are stored in the $ENVSDIR. They have names like $ENVSDIR/Django-1.6, $ENVSDIR/Python3, etc. Any time I want to switch to one, I just type switchenv [environment]. The usual tab completion rules apply; to list all environments, I type switchenv [TAB] [TAB].

Just a simple hack, but I’ve found it to be quite convenient. Enjoy!