If you’re juggling multiple Python projects, managing virtual environments can become a repetitive and error-prone task. Wouldn’t it be great if your Python virtual environment activated automatically whenever you navigated to your project directory? This guide will show you how to achieve just that using Zsh, making your development process smoother and more efficient.

Step 1: Create a Python Virtual Environment (venv)

First, ensure you have a Python virtual environment set up in your project’s directory. You can create a venv using the following command:

python3 -m venv /path/to/project/venv

Replace /path/to/project/venv with the actual path to your project directory where you want to create the virtual environment.

Step 2: Set Up Automatic Activation for a Specific Project

Next, we’ll configure your Zsh to automatically activate the virtual environment whenever you enter the project directory. Open your .zshrc file located in your home directory and add the following lines at the end:

# Activate Python venv when entering the "project" directory
activate_project_venv() {
    if [[ $PWD == /path/to/project* ]]; then
        source /path/to/project/venv/bin/activate
    fi
}

autoload -U add-zsh-hook
add-zsh-hook chpwd activate_project_venv

Replace /path/to/project with the actual path to your project directory. This script checks if your current directory matches the project path and activates the venv if it does.

Step 3: Set Up a More Generic Solution

For a more flexible setup that works for any project directory containing a virtual environment in a .venv subdirectory, add the following lines to your .zshrc file:

# Activate Python venv when entering a directory containing a ".venv" subdirectory
activate_venv_on_cd() {
    local venv_dir=".venv"
    if [[ -d "$PWD/$venv_dir" ]]; then
        source "$PWD/$venv_dir/bin/activate"
    fi
}

autoload -U add-zsh-hook
add-zsh-hook chpwd activate_venv_on_cd

This script checks if the current directory contains a .venv subdirectory and activates the virtual environment if it exists. This way, you can maintain a consistent structure across all your projects.