Skip to content

Instantly share code, notes, and snippets.

@afeld
Last active March 8, 2022 18:40
Show Gist options
  • Save afeld/4aefc7c9493f1519e141f52b40dc6479 to your computer and use it in GitHub Desktop.
Save afeld/4aefc7c9493f1519e141f52b40dc6479 to your computer and use it in GitHub Desktop.
automatic virtualenv switching

This script will automatically switch to a Python virtual environment after you cd into a Python project, then deactivate when you leave. Inspired by a similar script from Justin Abrahms.

Installation

  1. Install virtualenvwrapper.

  2. Download the auto_virtualenv.sh script, and put it in your home directory (~/).

  3. Run the following:

    chmod a+x ~/auto_virtualenv.sh
    echo "source ~/auto_virtualenv.sh" >> ~/.bash_profile
#!/bin/bash
# virtualenvwrapper setup
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=~/Envs
mkdir -p $WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh
# search recursively for a file in the current directory and all parent directories
function upsearch()
{
# adapted from http://stackoverflow.com/a/7614803/358804
find `( CP=${PWD}; while [ -n "$CP" ] ; do echo $CP; CP=${CP%/*}; done; echo /)` -mindepth 1 -maxdepth 1 -type f -name $1
}
function auto_virtualenv()
{
# check if directory changed
if [ "$PWD" != "$MYOLDPWD" ]; then
MYOLDPWD="$PWD"
REQUIREMENTS_PATH=$(upsearch requirements.txt)
if [[ "$REQUIREMENTS_PATH" ]]; then
# in a Python project
# http://stackoverflow.com/a/34109556/358804
CURRENT_PROJECT=$(awk -F/ '{ print $(NF-1) }' <<< "$REQUIREMENTS_PATH")
OLD_PROJECT=${VIRTUAL_ENV##*/}
# check if the project has changed, since `workon` is slow
if [ "$CURRENT_PROJECT" != "$OLD_PROJECT" ]; then
workon "$CURRENT_PROJECT"
fi
elif [ -n "$VIRTUAL_ENV" ]; then
# left a Python project
deactivate
fi
fi
}
# bash hook
PROMPT_COMMAND='auto_virtualenv'
# Mirrored support for zsh. See: https://superuser.com/questions/735660/whats-the-zsh-equivalent-of-bashs-prompt-command/735969#735969
function precmd()
{
eval "$PROMPT_COMMAND"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment