Skip to content

Instantly share code, notes, and snippets.

@Photonios
Last active September 25, 2019 22:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Photonios/4a17d6c952d85cc23234b4394b9becfc to your computer and use it in GitHub Desktop.
Save Photonios/4a17d6c952d85cc23234b4394b9becfc to your computer and use it in GitHub Desktop.
Auto-enter Python virtual environment.
# Finds a Python virtual environment in the current
# directory or any of its parents and enters it, or
# exits an virtual environment if we're in one
# but the current directory does not contain a virtualenv
function find_and_enter_virtualenv {
# See if the current directory, or any of its
# parents have a 'env/bin/activate' script
path=$(pwd)
while [ ! -z $path ]; do
if [ -f "$path/env/bin/activate" ]; then
path="$path/env/bin/activate"
break
fi
path="${path%/*}"
done
# No virtualenv found, try to de-activate
# in case we're exiting one
if [ -z $path ]; then
deactivate &> /dev/null
return
fi
# Enter the virtualenv
source $path
}
# Override `cd` so we can intercept directory changes
function cd {
builtin cd "$@"
find_and_enter_virtualenv
}
# Suppose a bash prompt is opened and that directory
# is a virtual env, we'll activate it!
find_and_enter_virtualenv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment