Created
January 13, 2017 16:35
-
-
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.
This file contains hidden or 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
# 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