Skip to content

Instantly share code, notes, and snippets.

@duke8585
Created October 8, 2025 10:21
Show Gist options
  • Save duke8585/f29b102c8821a6dbd0598d3dcaf05e24 to your computer and use it in GitHub Desktop.
Save duke8585/f29b102c8821a6dbd0598d3dcaf05e24 to your computer and use it in GitHub Desktop.
zsh auto activate deactivate .venv environment if found in a folder. make sure this is added to your `~/.alias` file and it is sourced in your `.zshrc` via e.g. `source ~/.alias`.
# NOTE auto activate .venv - https://stackoverflow.com/a/63955939
autoload -Uz add-zsh-hook
add-zsh-hook precmd automatically_activate_python_venv
function automatically_activate_python_venv() {
if [[ -z $VIRTUAL_ENV ]] ; then
activate_venv
else
parentdir="$(dirname ${VIRTUAL_ENV})"
if [[ "$PWD"/ != "$parentdir"/* ]] ; then
deactivate
activate_venv
fi
fi
}
function activate_venv() {
local d n
d=$PWD
until false
do
if [[ -f $d/.venv/bin/activate ]] ; then
source $d/.venv/bin/activate
break
fi
d=${d%/*}
# d="$(dirname "$d")"
[[ $d = *\/* ]] || break
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment