Today I learned how to use shell scripting to activate my virtual environment automatically when I change directories.
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 Icd
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?
The next cohort of the Intermediate Python Course starts soon.
Grab your spot now and learn the Python skills you've been missing!