Today I learned how to use shell scripting to activate my virtual environment automatically when I change directories.

Automatically activating virtual environments

Since I can remember, whenever I cd into a directory that contains a virtual environment folder .venv, I always want to activate that virtual environment. I typed source .venv/bin/activate so often that I even created an alias so that typing activate was enough.

Today, I wondered if there wasn't a way in which I could automatically run the command activate whenever I cd into a directory that contains a directory .venv. I was sure there was, so I opened ChatGPT and typed my question:

“In iterm2, how can I run the command activate automatically whenever I cd into a directory that contains a folder .venv?”

(iTerm2 is the terminal emulator I use.)

The output of the model turned out to be 99% of what I needed, and with a small tweak I ended up with this shell script that I added to my shell configuration file .zshrc:

# Generated by ChatGPT.
# This will automatically run the command `activate` when I
# `cd` into a directory that contains a directory `.venv`.
cd() {
    builtin cd "$@" || return  # Use the built-in cd command and handle errors
    if [ -d ".venv" ]; then
        if [ -f ".venv/bin/activate" ]; then
            echo "Activating virtual environment in $(pwd)"
            activate
        else
            echo ".venv directory found, but no activate script exists."
        fi
    fi
}

Now, whenever I cd into a directory with a .venv, I see the message “Activating virtual environment in (...)” and the environment activates! Isn't technology wonderful?

Become a better Python 🐍 developer 🚀

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book “Pydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here 🐍🚀.

Previous Post Next Post

Blog Comments powered by Disqus.