Posted 2011-11-22T19:16:00+01:00 in unix

Auto-source the local virtualenv environment

Okay, here's a small itch that I just had to scratch: I have various projects set up with Ian Bicking's virtualenv. Virtualenv is a tool to create isolated Python environments. You need to load a few environment settings in your shell to make virtualenv grok your "virtual environment". I usually just run . bin/activate in my shells after I cd to the project directory, but it becomes a bit bothersome when you have more than 5 shells and more than two projects open at the same time.

Here's a small Bash shell function that adds some steroids to the cd builtin so that it automagically sources the virtualenv settings and deactivates them when you leave the virtualenv'ed directory. This is automagic, and may not be to everyones tastes. Append it to your .bash_profile and "you're all set", as they say in the US of A.

cd ()
{
    builtin cd "$@"
    RETVAL=$?
    # Test for successful real cd:
    if [ 0 -ne $RETVAL ]; then
        return $RETVAL
    fi
    # Deactivate once I move outside the virtualenv directory or 
    # do nothing when I'm still in this same virtualenv directory
    # (Assuming no one nests virtualenvs....)
    if [ ! -z "$VIRTUAL_ENV" ]; then
        if [ "$PWD" = "${PWD#$VIRTUAL_ENV}" ]; then
            deactivate
        else
            return 0
        fi
    fi
    # "Detect" virtualenv files:
    if [ -r "bin/activate" ]; then
        if head -n 1 "bin/activate" | grep -q 'source bin/activate' > /dev/null; then
            source "bin/activate"
        fi
    fi
    return 0
}

I haven't tried the function in other shells than Bash. It may very well not work. Do 'unset cd' or 'unalias cd' in that case, methinks.