It's not a new or original idea – I've heard about it from
Dmitry Gladkov but as usual didn't remember details. So, I've created my own implementation of activation/deactivation of python
virtualenv:
#!/bin/bash
PREVPWD=`pwd`
PREVENV_PATH=
PREV_PS1=
PREV_PATH=
handle_virtualenv(){
if [ "$PWD" != "$PREVPWD" ]; then
PREVPWD="$PWD";
if [ -n "$PREVENV_PATH" ]; then
if [ "`echo "$PWD" | grep -c $PREVENV_PATH`" = "0" ]; then
source $PREVENV_PATH/.venv
echo "> Virtualenv `basename $VIRTUALENV_PATH` deactivated"
PS1=$PREV_PS1
PATH=$PREV_PATH
PREVENV_PATH=
fi
fi
# activate virtualenv dynamically
if [ -e "$PWD/.venv" ] && [ "$PWD" != "$PREVENV_PATH" ]; then
PREV_PS1="$PS1"
PREV_PATH="$PATH"
PREVENV_PATH="$PWD"
source $PWD/.venv
source $VIRTUALENV_PATH/bin/activate
echo "> Virtualenv `basename $VIRTUALENV_PATH` activated"
fi
fi
}
export PROMPT_COMMAND=handle_virtualenv
Just paste this code into your
$HOME/.bash_profile
and place
.venv
file with declaration like below:
VIRTUALENV_PATH=$HOME/.envs/sampleenvironment
And it should works like a charm.
Script only for bash!