Skip to content

Instantly share code, notes, and snippets.

@mikeckennedy
Created August 12, 2025 00:38
Show Gist options
  • Save mikeckennedy/6c6fd9191879fba77a334f13aa4ad3d3 to your computer and use it in GitHub Desktop.
Save mikeckennedy/6c6fd9191879fba77a334f13aa4ad3d3 to your computer and use it in GitHub Desktop.
Auto-activate Python virtual environment for any project with a venv directory in your shell (macOS/Linux).
# Include this in your shell *rc file (e.g. .bashrc, .zshrc, etc).
# Update the folder name to your convention.
# This uses venv as the virtual environment name, but if you use .venv, change it in the script.
# Auto-activate virtual environment for any project with a venv directory
function chpwd() {
# Function to find venv directory in current path or parent directories
local find_venv() {
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -d "$dir/venv" && -f "$dir/venv/bin/activate" ]]; then
echo "$dir/venv"
return 0
fi
dir="$(dirname "$dir")"
done
return 1
}
local venv_path
venv_path=$(find_venv)
if [[ -n "$venv_path" ]]; then
# We found a venv, check if it's already active
if [[ "$VIRTUAL_ENV" != "$venv_path" ]]; then
# Deactivate current venv if different
if [[ -n "$VIRTUAL_ENV" ]]; then
deactivate
fi
# Activate the found venv
source "$venv_path/bin/activate"
local project_name=$(basename "$(dirname "$venv_path")")
echo "✅ Activated virtual environment for: $project_name"
fi
else
# No venv found, deactivate if we have one active
if [[ -n "$VIRTUAL_ENV" ]]; then
local project_name=$(basename "$(dirname "$VIRTUAL_ENV")")
deactivate
echo "�� Deactivated virtual environment for: $project_name"
fi
fi
}
# Also run the function when the shell starts
chpwd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment