2024-04-10

Activate Python virtual environment automatically on iTerm2

I set iTerm2 to open same directory for a new tab.

iTerm2: Preferences -> Profiles -> Working Directory -> Advanced Configuration -> Working Directory for New Tabs: "Reuse previous sessions's directory"

Today as I work with Python code, I noticed I open a new tab and activate the virtual environment in a newly opened tab each time. Although it was aliased to just "activate", it was still an extra step to go through that can be automated.

# ~/.zshrc
# before
alias activate="source .venv/bin/activate"

BTW, virtual environment directory name is set to ".venv" as it's the one that's generated by uv.

# ~/.zshrc
alias createvenv="uv venv && source .venv/bin/activate"

Here's how to automate this.

1. Create a function in the .zshrc

# ~/.zshrc
# after
activate() {
  if [ -d ".venv" ]; then
    source .venv/bin/activate
  else
    : # ignore if no .venv
  fi
}

This will replace the above alias "activate"; it is essentially the same but by using this function, we can ignore following error message when there is no virtual environment (i.e. ".venv")

# error message
source: no such file or directory: .venv/bin/activate

TIL. I can make a shell script/function inside .zshrc instead of making a separate *.sh file.

2. Set iTerm to call this function on a new tap

iTerm2: Preferences -> Profiles -> Command: Login Shell -> Send text at start: "activate"