Setting Up a Python Virtual Environment

This articles is a quick do-it-yourself (DIY) guide on setting up a virtual environment on your computer for scripting with Python.

Why would you want to setup a virtual environment?

Setting up a virtual environment allows you to separate different code bases for different needs. For example, you may have some scripts that run on Python 2.7 and others (hopefully most of them) that run on Python 3.5 or higher. A virtual environment allows you to easily switch from one to the other, also installing packages in each one separately.

3 Easy Steps

1 - Install Python if you haven’t already

Python 2.7 comes pre-installed on Mac OS X. Most of the scripts I write would run on python 2.7 with minimal effort. That being said, I highly recommend installing and running Python 3.5 or higher.

2 - Install mkvirtualenv ^[These instructions are adapted from a post at http://exponential.io/blog/2015/02/10/install-virtualenv-and-virtualenvwrapper-on-mac-os-x/]

mkvirtualenv is an essential command for setting up virtual environments. It makes it easy to enter and exit them anywhere in the terminal.

Open a terminal and install run the following command

sudo pip install virtualenv virtualenvwrapper

Setup virtualenvwrapper in ~/.bash_profile.

The next thing you do is setup some terminal values that make the virtual environments easy to enter.

Enter the following commands in your terminal First, create a backup of your .bash_profile

cp ~/.bash_profile ~/.bash_profile-org

# Be careful with this command printf '\n%s\n%s\n%s' '# virtualenv' 'export WORKON_HOME=~/virtualenvs' \ 'source /usr/local/bin/virtualenvwrapper.sh' >> ~/.bash_profile

Enable the virtual environment system. This only needs to be done once. It will be activated each time you start a terminal session from now on.

source ~/.bash_profile

3 - Create a virtualenv

Now that mkvirtualenv is installed, we can use it to, well, make a virtualenv. The following command create a virtualenv called api.

mkvirtualenv api

After a virtualenv is created, the environment will automatically be loaded. You can see the virtualenv that is loaded by looking at your terminal command. For example, I have a virtualenv called v3 for most of my Python 3 stuff. My terminal is prefixed with (v3) when I am working in this environment.

Picture of Prefixed Virtual Env - CLI

Tips on Working with a virtual environment

The following are useful commands when workign with a virtual environment.

deactivate

To enable the api virtual environment, run the following command any where in the terminal:

workon api

To deactivate the api virtual environment, run the following command:

deactivate

And voila!. You now have a functioning virtual environment setup for your Python scripting needs.