Skip to content

Instantly share code, notes, and snippets.

@mdonkers
Created January 8, 2016 13:34
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 mdonkers/8749a10fcee6c99ed333 to your computer and use it in GitHub Desktop.
Save mdonkers/8749a10fcee6c99ed333 to your computer and use it in GitHub Desktop.
Activates Python virtualenv. Use as "$ source activate_environment.sh <virtualenv_directory>". Will also update the prompt, to show which virtualenv environment is active, and reset the prompt when no longer active. Assumes command-prompt is already created with git-prompt; https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
#!/bin/bash
## Call with 'source activate_environment.sh <env>'
function check_sourced {
local last_elem=${#FUNCNAME[@]}-1
if [[ "main" == ${FUNCNAME[$last_elem]} ]] ; then
echo "Being executed from a sub-shell, which won't set the environment correctly"
echo "Execute as 'source activate_environment <env>' or '. activate_environment <env>'"
exit
fi
}
check_sourced
if [[ ! -z $1 && -d $1 && -f "$1/bin/activate" ]] ; then
echo "Activating virtualenv $1"
source "$1/bin/activate"
VENV_NAME=${1%/}
if [[ -z $PREV_PROMPT_COMMAND ]] ; then
PREV_PROMPT_COMMAND=$PROMPT_COMMAND
fi
function set_venv_prompt {
if [[ ! -z $VIRTUAL_ENV ]] ; then
__git_ps1 "\h:\W (env:$VENV_NAME) \[\033[00;34m\]" "\[\033[00m\] \u\\\$ "
else
PROMPT_COMMAND=$PREV_PROMPT_COMMAND
unset PREV_PROMPT_COMMAND
eval $PROMPT_COMMAND
fi
}
PROMPT_COMMAND="set_venv_prompt"
echo "Deactivate the virtualenv environment by typing 'deactivate' or exiting the shell"
return 0
fi
echo "Provide a valid virtualenv environment to activate"
return 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment