Before you begin:

Note that the latest release of OSX (currently High Sierra) comes with Python 2.7, but the official documentation seems to suggest that it is worth installing it via Homebrew anyway. The reason for this is that installing Python with Homebrew will also install the pip package manager, which is not installed with the native OSX version.

Installing Python 2 on OSX with Homebrew

With Homebrew installed (and having run brew update), the first part of the installation is really straightforward:

brew install python@2

What is the @2? It is distinguishes between Python 2.x and Python 3.x.

Additional checks:

  • To check the install worked, run
which python

and if the output is /usr/local/bin/python, then the installation worked!

/usr/local/bin/python

Installing Python modules:

Update: there seems to be anew way of installing with pip:

python2 -mpip install numpy
python2 -mpip install scipy
python2 -mpip install matplotlib
python2 -mpip install pandas
python2 -mpip install sklearn
python2 -mpip install cython
pip2 install ipython[all]

It seems that the command python2 -mpip install ipython does not work.

Previous method for installing modules:

  • Run the following:
brew linkapps
  • Run this to install the updated GCC and Fortran compiler:
brew install gcc --use-llvm
  • Before installing any Python modules, you should do the following:
brew tap homebrew/science
brew tap homebrew/python
brew tap homebrew/dupes

Run the following to install a few useful Python modules:

pip install numpy
pip install scipy
pip install matplotlib
pip install pandas
pip install scikit-learn
pip install cython
pip install ipython[all]

Credit: most of these commands came from a script created by my colleague, Felipe Llinares López.

Check installation

Check that ipython is installed on the command line:

ipython

Quit by using the quit() command.

Check that the Jupyter notebook is installed:

ipython

Quit by pressing Ctrl-C twice.

For the other packages, you can try loading them from the command line, or run the script eg_python.py.

import numpy as np
import scipy as s
import pandas as pd
import sklearn as sk

#https://matplotlib.org/examples/lines_bars_and_markers/scatter_with_legend.html
import matplotlib.pyplot as plt
from numpy.random import rand

fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color, alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

Download the script and run as:

python eg_python.py

If everything is installed correctly, a figure should appear, something like the one below. That's it, enjoy Python!

matplotlib figure