Skip to content

Instantly share code, notes, and snippets.

@tartley
Last active December 2, 2025 15:08
Show Gist options
  • Select an option

  • Save tartley/953bea073c2e8f830ad3eba078b6e238 to your computer and use it in GitHub Desktop.

Select an option

Save tartley/953bea073c2e8f830ad3eba078b6e238 to your computer and use it in GitHub Desktop.
Automatically activate/deactivate virtualenvs in `.venv` when we `cd` into their parent directory
# auto activate virtualenvs ------------------
# I suspect this could be rewritten to just use VIRTUAL_ENV directly,
# without needing the $parentdir variable at all.
function cd() {
builtin cd "$@"
# If we move out of a previous parentdir, deactivate the previous venv
if [[ -n "$parentdir" && "$PWD"/ != "$parentdir"/* ]]; then
deactivate
unset parentdir
fi
# If there is a virtualenv, activate it
if [[ -d ".venv" && -f ".venv/bin/activate" ]]; then
source ".venv/bin/activate"
parentdir="$(dirname $VIRTUAL_ENV)"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment