Last active
September 25, 2019 22:20
-
-
Save Photonios/4a17d6c952d85cc23234b4394b9becfc to your computer and use it in GitHub Desktop.
Auto-enter Python virtual environment.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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