PyCharm VirtualEnv ZSH Terminal

Despite numerous requests from thier userbase, JetBrains has yet to implement automatic virtualenv activation in the integrated Terminal window when in a project view. This post shows how to achieve this goal using zsh & Mac OS.

We are going to utilize the fact that the embedded Terminal sessions are always initiated from the home directory of an opened project. In order for this solution to work, the name of a virtualenv directory will need to be the same as the name of our project’s home folder. Also, all the virtualenvs will have to reside in the same directory.

In my case I’m going to use ~/dev/venv as the common place for all the venvs:

➜  ~ cd dev
➜  dev mkdir venv

Our example project is called crm, we will therefore need a matching virtual environment:


Once it’s ready, I need to rebuild all the libraries my project needs to run. Because one of these dependencies is psycopg2, I will run pip manually, reusing the PostgreSQL installation from my previous posts on PG-Strom:

➜  dev source venv/crm/bin/activate
(crm) ➜  dev export PATH=/Users/tompaw/postgres/bin:$PATH
(crm) ➜  dev pip install -r manganium/crm/requirements.txt

The next step is to prepare an RC directory, which will be passed over to ZSH using the ZDOTDIR environmental variable:

➜  ~ mkdir pycharm_rc

Inside this dir, we’re going to have a .zshrc file:

➜ ~ cat pycharm_rc/.zshrc 
source ~/.zshrc
source ~/dev/venv/$vdir/bin/activate

What it does is:

  1. Invoke the original ~/.zshrc script.
  2. Get the name of our project home directory and put it in a vdir variable.
  3. Activate the virtual environment at ~/dev/venv/$vdir.

In order for zsh to execute this particular .zshrc on launch, it needs to have its directory in the ZDOTDIR variable. Unfortunately, PyCharm does not support the “FOO=bar /bin/zsh” notation, so we need a wrapper script to launch it:

➜ ~ cat pycharm_rc/activate
export ZDOTDIR=~/pycharm_rc

This file should be executable:

➜ ~ chmod +x pycharm_rc/activate

What remains now is to stick our wrapper inside the “Shell Path” parameter of Terminal configuration with PyCharm:


Et Voilà! We can now jump right into each project’s own Virtual Environment:


Leave a Reply

Your email address will not be published. Required fields are marked *