Skip to content

Instantly share code, notes, and snippets.

@cristovaov
Last active August 12, 2016 22:21
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 cristovaov/bbd79956d7e1ee0b9897 to your computer and use it in GitHub Desktop.
Save cristovaov/bbd79956d7e1ee0b9897 to your computer and use it in GitHub Desktop.
Crude script to activate a Python virtual environment in Git Bash. Probably works w/ MSYS2, not sure on Cygwin -> needs usecases.
# Usage like activating venv on Linux: source /path/to/env/Scripts/activate
# Use 'deactivate_venv' on CL or pass argument '--deactivate' on the source command to deactivate env.
deactivate_venv() {
if [[ -z ${_OLD_VIRTUAL_PATH} ]]; then
printf "No virtual environment found!\n"
else
export PATH=$_OLD_VIRTUAL_PATH
export PS1=$_OLD_VIRTUAL_PS1
unset _OLD_VIRTUAL_PATH
unset _OLD_VIRTUAL_PS1
unset VIRTUAL_ENV
printf "Python virtual environment deactivated!\n"
fi
}
activate_venv() {
__VIRTUAL_BIN__=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
VIRTUAL_ENV=$(sed -n '2p' "${__VIRTUAL_BIN__}/activate.bat")
export $(echo "$VIRTUAL_ENV" | sed -e 's/set //' -e 's/\"//g')
export _OLD_VIRTUAL_PATH=$PATH
export PATH=$__VIRTUAL_BIN__:$PATH
export _OLD_VIRTUAL_PS1=$PS1
export PS1='\[\033]0;$TITLEPREFIX:${PWD//[^[:ascii:]]/?}\007\]\n\[\033[32m\]\u@\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n(`basename $VIRTUAL_ENV`) \$ '
printf "Python virtual environment activated in %s\n" "$VIRTUAL_ENV"
}
main() {
if [[ $1 == "--deactivate" ]]; then
deactivate_venv
else
deactivate_venv
activate_venv
fi
}
main "$@"
# V20160813: append venv dir to PS1
# V20160312: strange line number thingie...
# V20160308: added deactivation method
# V20160307: It's-a-Bash! WINDOWS ONLY!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment