Skip to content

Instantly share code, notes, and snippets.

@jtratner
Last active December 19, 2015 09:39
Show Gist options
  • Save jtratner/5934189 to your computer and use it in GitHub Desktop.
Save jtratner/5934189 to your computer and use it in GitHub Desktop.
Transparent virtualenv switching with Git and zsh
  • Source p, virtualenv.zsh, auto-workon.sh in your .zshrc
  • Put _p in your fpath. (e.g., /usr/share/zsh/site-functions)
  • Change PYTHONPROJECTS in virtualenv.zsh to the base directory for your Python projects.
  • Now you can use p <projectname> to get to a project and switch to its virtualenv and p alone to deactivate your virtualenv entirely. Plus you now have tab completion into your projects - yay!
#compdef p
_files -W $PYTHONPROJECTS/$1 -/
# Automatically activate Git projects' virtual environments based on the
# directory name of the project. Virtual environment name can be overridden
# by placing a .venv file in the project root with a virtualenv name in it
# written by Harry Marr @ http://hmarr.com/2010/jan/19/making-virtualenv-play-nice-with-git/
function workon_cwd {
# Check that this is a Git repo
GIT_DIR=`git rev-parse --git-dir 2> /dev/null`
if [[ $? == 0 ]]; then
# Find the repo root and check for virtualenv name override
GIT_DIR=`\cd $GIT_DIR; pwd`
PROJECT_ROOT=`dirname "$GIT_DIR"`
ENV_NAME=`basename "$PROJECT_ROOT"`
if [ -f "$PROJECT_ROOT/.venv" ]; then
ENV_NAME=`cat "$PROJECT_ROOT/.venv"`
fi
# Activate the environment only if it is not already active
if [[ "$VIRTUAL_ENV" != "$WORKON_HOME/$ENV_NAME" ]]; then
if [ -e "$WORKON_HOME/$ENV_NAME/bin/activate" ]; then
workon "$ENV_NAME" && export CD_VIRTUAL_ENV="$ENV_NAME"
fi
fi
elif [ $CD_VIRTUAL_ENV ]; then
# We've just left the repo, deactivate the environment
# Note: this only happens if the virtualenv was activated automatically
deactivate && unset CD_VIRTUAL_ENV
fi
}
# New cd function that does the virtualenv magic
function venv_cd {
cd "$@" && workon_cwd
}
venv_cd $PYTHONPROJECTS/$1
# Change this to the basedirectory of your python projects
export PYTHONPROJECTS="$HOME/projects/python"
# Useful virtualenv settings
export WORKON_HOME="$HOME/.virtualenvs"
export VIRTUALENV_USE_DISTRIBUTE=true
export VIRTUALENVWRAPPER_HOOK_DIR="$HOME/.virtualenvs"
export VIRTUALENVWRAPPER_LOG_DIR="$HOME/.virtualenvs"
export PIP_VIRTUALENV_BASE=$WORKON_HOME
export PIP_RESPECT_VIRTUALENV=true # best option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment