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
activateautomatically whenever Icdinto 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?
Get a daily drop of Python knowledge. A short, effective tip to start writing better Python code: more idiomatic, more effective, more efficient, with fewer bugs. Subscribe here.