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.

Revisions

  1. mikeckennedy created this gist Aug 12, 2025.
    48 changes: 48 additions & 0 deletions auto_python_venv.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    # 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