Last Updated: February 25, 2016
·
616
· reorx

A smart `cd` for your Python project

I use virtualenv and virtualenvwrapper to manage with my Python projects, but swapping to different virtual environment when entering in project folders is boring and easy to forget, so I redefine the cd command like this:

use_virtualenv() {
    if [ -e .virtualenv ]; then
        name=$(cat .virtualenv)
        if [ $VIRTUAL_ENV ]; then
            if [ "$name" = "$(basename $VIRTUAL_ENV)" ]; then
                return
            fi
        fi
        workon $name
    fi
}
cd () {
    builtin cd "$@" && use_virtualenv
}

# Call the function on .zshrc loaded
use_virtualenv

When I have a project that use a virtual environment, for example, TORNADO, I write it to a file named .virtualenv in the project's root folder:

cd /my/project/folder
echo TORNADO > .virtualenv

everytime I enter in this folder by cd, the virtualenv will automatically be swapped to TORNADO, never bother typing workon again and again =D

Note. This trick is working only for zsh, if you are using other shells like bash, please change the code to fit yours.