Skip to content

Instantly share code, notes, and snippets.

@perbu
Created October 24, 2019 16:54
Show Gist options
  • Save perbu/4748d723bb22fa00356ed25193ec9cd9 to your computer and use it in GitHub Desktop.
Save perbu/4748d723bb22fa00356ed25193ec9cd9 to your computer and use it in GitHub Desktop.
#!/bin/zsh
#
# Auto activate a python virtualenv when entering the project directory.
# Installation:
# source virtualenv-auto-activate.sh
#
# Usage:
# Function `venvconnect`:
# Connect the currently activated virtualenv to the current directory.
#
VENV_HOME=$HOME/.virtualenvs
function _virtualenv_auto_activate() {
if [[ -f ".venv" ]]; then
_VENV_PATH=$VENV_HOME/$(cat .venv)
# Check to see if already activated to avoid redundant activating
if [[ "$VIRTUAL_ENV" != $_VENV_PATH ]]; then
source $_VENV_PATH/bin/activate
fi
fi
}
function venvconnect (){
if [[ -n $VIRTUAL_ENV ]]; then
echo $(basename $VIRTUAL_ENV) > .venv
else
echo "Activate a virtualenv first"
fi
}
chpwd_functions+=(_virtualenv_auto_activate)
precmd_functions=(_virtualenv_auto_activate $precmd_functions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment