Skip to content

Instantly share code, notes, and snippets.

@akiross
Created January 13, 2017 16:35
Show Gist options
  • Save akiross/bbec88de9d72362b12c7aa3d4546c9f2 to your computer and use it in GitHub Desktop.
Save akiross/bbec88de9d72362b12c7aa3d4546c9f2 to your computer and use it in GitHub Desktop.
A very handy function to auto-activate specific python virtual environments upon entering a directory containing a magic file.
# Setup python virtual environment in a given directory subtree
function chpwd_auto_pyvenv() {
local MAGIC=".zsh_pyvenv"
# Check if we encountered a magic previously
if [[ -z ${ZSH_PYVENV_PARENT+x} ]]; then
# Check if this directory contains a MAGIC
if [[ -a "$PWD/$MAGIC" ]]; then
echo "Activating virtual environment"
# Activate the environment specified
source "$(<$PWD/$MAGIC)/bin/activate"
# Save the current directory
export ZSH_PYVENV_PARENT=$PWD
else
# No MAGIC here...
fi
else
# Check whether PWD is a subfolder of ZSH_PYVENV_PARENT
case $PWD/ in
$ZSH_PYVENV_PARENT/*)
# Yes, we are in a subdir
echo "Entering virtual environment subdir..."
;;
*)
# No, we left the MAGIC tree
echo "Leaving virtual environment"
deactivate
unset ZSH_PYVENV_PARENT
;;
esac
fi
}
chpwd_functions=(${chpwd_functions[@]} "chpwd_auto_pyvenv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment