Monday, January 6, 2025

How to automatically launch venv in folder

 use below for Mac:

# Function to manage venv activation and deactivation
function manage_repoenv_venv() {
    # Root project directory and virtual environment path
    PROJECT_DIR="/Users/your_username/code/repo"  # Update the path for macOS
    VENV_PATH="$PROJECT_DIR/repoenv/bin/activate"

    # Check if the current directory or any subdirectory is within the project directory
    if [[ "$PWD" == "$PROJECT_DIR"* ]]; then
        # Activate venv if not already activated
        if [ -z "$VIRTUAL_ENV" ]; then
            source "$VENV_PATH"
        fi
    else
        # Deactivate the venv if active and leaving the project directory
        if [ -n "$VIRTUAL_ENV" ] && [[ "$VIRTUAL_ENV" == "$PROJECT_DIR/repoenv" ]]; then
            deactivate
        fi
    fi
}

# Hook into directory changes for Zsh
function precmd() {
    manage_repoenv_venv
}

# Source the script
source ~/.zshrc


for BASH:

PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND; }manage_kfenv_venv"

No comments:

Post a Comment