> /dev/null

Interesting hacks, snippets, and shortcuts.

Nov 7

Quickly activate a virtualenv

Here is a small bash function that serches for a virtualenv on your current path and activates it for you. To use it, simply type ve. If your virtualenv is named something besides 've', pass its name as the first argument: ve my_env.

ve() {
    local curdir ve
    curdir="$PWD"
    [ -z "$1" ] && ve="ve" || ve="$1"
    while ! ls -d "$ve" >/dev/null 2>&1; do
        if [ "$PWD" == "/" ]; then
            echo "Cannot find a '$ve' directory on the current path" >&2
            cd $curdir
            return -1
        fi
        cd ..
    done
    echo "Using $PWD"
    source "$ve/bin/activate"
    cd "$curdir"
}