Had this issue today. The current answer doesn't address the fact that the environment is activated every time you cd
into a subfolder or back to the root folder. Solved it with the following .env
script:
venv=venv
currentvenv=""
if [[ $VIRTUAL_ENV != "" ]]
then
# Strip out the path and just leave the env name
currentvenv="${VIRTUAL_ENV##*/}"
fi
if [[ "$currentvenv" != "$venv" ]]
then
echo "Switching to environment: $venv"
workon $venv
#else
# echo "Already on environment $venv"
fi
Replace venv
with the name of your environment. You can uncomment the else block to see that it doesn't try to activate the environment every time, given that the desired environment is already activated.
Note: If you're not using virtualenvwrapper
then you should replace the workon
command with whatever command you're using to activate your virtual environment. I do recommend using virtualenvwrapper
though.