Skip to content

Instantly share code, notes, and snippets.

@fgimian
Created August 4, 2015 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgimian/c80a66183cc7d0d5f622 to your computer and use it in GitHub Desktop.
Save fgimian/c80a66183cc7d0d5f622 to your computer and use it in GitHub Desktop.
Automatic virtualenv switching for virtualenvwrapper
# Automatic activation and deactivation of virtualenvs using virtualenvwrapper
# whereby the virtualenv name must match the current directory name
function cd
{
# Perform the regular cd
builtin cd "$@"
# Iterate through the current directory, heading into each parent directory
# until we find a .virtualenv file or land in the top directory (/)
test_directory=$(pwd)
while [ "$test_directory" != "/" ]
do
# The .virtualenv definition was found
if [ -f $test_directory/.virtualenv ]
then
virtualenv=$(cat $test_directory/.virtualenv)
# The virtualenv is not yet activated
if [ -z $VIRTUAL_ENV ] || [ $VIRTUAL_ENV != $WORKON_HOME/$virtualenv ]
then
if [ -f $WORKON_HOME/$virtualenv/bin/activate ]
then
source $WORKON_HOME/$virtualenv/bin/activate
else
echo "The virtualenv $virtualenv doesn't exist, unable to activate"
fi
fi
break
else
test_directory=$(dirname "$test_directory")
fi
done
# If no virtualenv was found and one is already activated, we deactivate
# it for the user
if [ "$test_directory" == "/" ] && [ ! -z $VIRTUAL_ENV ] && \
[[ $VIRTUAL_ENV == $WORKON_HOME/* ]]
then
deactivate
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment