Skip to content

Instantly share code, notes, and snippets.

@obar1
Last active April 28, 2025 08:25
Show Gist options
  • Save obar1/212e4c778548f8bcdc6e9c1b05856f3f to your computer and use it in GitHub Desktop.
Save obar1/212e4c778548f8bcdc6e9c1b05856f3f to your computer and use it in GitHub Desktop.
for bashrc to automaticaly activate and deactivate venv in folders as you move between them
function check_venv() {
# Check if we're entering a directory with a .venv
if [ -d "./venv" ]; then
echo "!!! deleting venv "
rm -rf venv
fi
if [ -d "./.venv" ]; then
if [ -n "$OLDPWD" ] && [ "$PWD" != "$OLDPWD" ]; then
echo "folder changed..."
python_path=$(which python 2>/dev/null)
# skip if def python is active
if [ -n "$python_path" ] && [[ ! "$python_path" =~ "$PWD/.venv/bin/python" ]]; then
if [ -n "$python_path" ] && [[ ! "$python_path" =~ "/usr/bin/python" ]]; then
which python
deactivate
echo "deactivated..."
fi
source ./.venv/bin/activate
which python
echo "ACTIVATED..."
fi
fi
fi
}
# Set PROMPT_COMMAND to call the function before each prompt
PROMPT_COMMAND="check_venv"
@obar1
Copy link
Author

obar1 commented Apr 28, 2025

ex of usage
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment