Created
August 4, 2015 13:42
-
-
Save fgimian/c80a66183cc7d0d5f622 to your computer and use it in GitHub Desktop.
Automatic virtualenv switching for virtualenvwrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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