Last active
January 17, 2025 16:59
-
-
Save ScottJWalter/7a67f1164cf7feb7696b00c2b9e01a90 to your computer and use it in GitHub Desktop.
Activate/deactivate venv as you move around the directory tree
This file contains 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
#!/bin/sh | |
# add to .bashrc/.zshrc/... to wrap the cd command with a venv check | |
# NOTE: This assumes '.venv' is the virtual environment directory | |
# | |
function cd() { | |
builtin cd "$@" | |
if [[ -z "$VIRTUAL_ENV" ]] ; then | |
## If env folder is found then activate the vitualenv | |
if [[ -d ./.venv ]] ; then | |
source ./.venv/bin/activate | |
fi | |
else | |
## check the current folder belong to earlier VIRTUAL_ENV folder | |
# if yes then do nothing | |
# else deactivate | |
parentdir="$(dirname "$VIRTUAL_ENV")" | |
if [[ "$PWD"/ != "$parentdir"/* ]] ; then | |
deactivate | |
fi | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment