Setting up Python on Mac OS X takes a few steps, which will allow you to configure a sane environment that won’t mess up the pre-shipped version of Python.
Remove any old environments
Make sure to remove old installations of Python, if previously installed on your system, except for the one installed by Mac OS X. For example, if we previously installed Python from homebrew, then the uninstall commands are:
1
2
3
|
brew uninstall virtualenv
brew uninstall virtualenvwrapper
brew uninstall python
|
If you installed python via the OS’s python (for example, the one coming from Mac), then:
1 |
sudo pip uninstall virtualenv virtualenvwrapper
|
A side effect of removing previous Python installations is also removing project-specific virtualenv‘s. If you have created requirements.txt files for these environments, it should be straightforward to rebuild them later.
Installing the new environments
Since many versions of Python have been shipped, it’s wise to choose a recent installation of 2.7 and 3.5. We’ll use a environment tool to properly build and install the right version of Python. We will be using pyenv tool. We don’t use homebrew because it doesn’t list all available versions.
1. Install homebrew for Mac if you don’t have it.
1 |
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
|
2. Install pyenv using homebrew:
1
2
3
4
|
brew update
brew install pyenv
brew install pyenv-virtualenv
brew install pyenv-virtualenvwrapper
|
3. Let’s configure Pyenv correctly in your terminal’s ~/.bash_profile (~/.bashrc on Ubuntu). Add the following lines if not already there in the file:
1
2
3
4
|
# Python from pyenv
if which pyenv > /dev/null; then eval "$(pyenv init -)"; fi
if which pyenv-virtualenv-init > /dev/null; then eval "$(pyenv virtualenv-init -)"; fi
pyenv virtualenvwrapper
|
4. After installing the prerequisites, now we’ll use pyenv to install Python. Please choose one of the following steps to follow, depending on which Python you wish to install. Also, if you are using certain packages such as bcrypt, use the alternative install steps.
Regular install steps for Python 2.7.
1
2
3
|
# Python 2
pyenv install 2.7.10
pyenv global 2.7.10
|
Steps for installing Python with bcrypt package (see bug report).
1
2
3
|
# Python 2
PYTHON_CONFIGURE_OPTS="--enable-unicode=ucs2" pyenv install 2.7.10
pyenv global 2.7.10
|
Regular install steps for Python 3.5.
1
2
3
|
# Python 3
pyenv install 3.5.1
pyenv global 3.5.1
|
5. To configure virtual environments for project-specific Python dependencies:
1
2
3
4
5
6
|
mkvirtualenv <your env name>
workon <your env name>
# … Do your work ...
source deactivate
|
Gotcha: We have to use the pyenv version of virtualenv and virtualenvwrapper. The non-pyenv version won’t work: it will stop your terminal from opening (See bug report).