virtualenvwrapper in osx

Using python virtual env wrapper is very beneficial, especially when you have many python projects using different python versions. It would be a disaster if we just blindly pip install all project modules into our global site-packages. There will definitely be package conflicts later on. Using a virtual environment will keep your python modules stored separately per environment, thus avoiding many issues mentioned above.

To install virtualenvwrapper, just do pip install virtualenvwrapper. Or follow this doc.

Then add the following to your .bash_profile file.

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/

Then run source ~/.bash_profile

If you are getting error like the following, perhaps your system is confused about which python you are using. Try reading
this. I am using python3, so I fixed the issue by sudo /usr/local/bin/pip3 install virtualenv virtualenvwrapper

/usr/bin/python: No module named virtualenvwrapper There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
set properly.

Before setting up a new virtual environment, I recommend to determine your python version first. Sometimes projects will have python version dependency and so do the rest of the python modules. So use `which python` or so to figure out the path to your python. For us let’s say we will stick with python 2.7, so we use /usr/bin/python. Double check by /usr/bin/python –version.

To make a new virtual environment, it is just one command away. I usually name it by the name of the project folder/repo.

mkvirtualenv -p /usr/bin/python my_project

The mkvirtualenv command will create ~/.virtualenvs/my_project. In its bin folder, you will see the python2.7 symlink. Next to the bin folder is the lib folder. All your future pip install modules will go into ~/.virtualenvs/my_project/lib/python2.7/site-packages/.

You will notice (my_project) appears on the left side of your command prompt. This is to signal that we are in the my_project virtual environment. (mkvirtualenv did a workon at the end of its execution.) Now if you do a pip install, the package files will get saved at ~/.virtualenvs/my_project/lib/python2.7/site-packages/.

When you want to exit the my_project virtual environment, do


Then you will be back to your global environment, or your normal bash shell.

So the workflow is

workon my_project
# do stuff

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s