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.
BTW, virtual environment directory name is set to ".venv" as it's the one that's generated by uv.
Here's how to automate this.
1. Create a function in the .zshrc
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")
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
"