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?

Improve your Python 🐍 fluency and algorithm knowledge 🎯

Get ready for 12 intense days of problem-solving. The “Algorithm Mastery Bootcamp” starts December 1st and it will feature 24 programming challenges, live analysis sessions, a supportive community of like-minded problem-solvers, and more! Join now and become the Python expert others can rely on.

Previous Post Next Post

Blog Comments powered by Disqus.