Installation of GDAL and its Python Libraries on Mac

Page content

Recently I have been trying to install GDAL on my Mac and I cannot find a way to link the Python libraries to the Python program I am using so that I can import GDAL libraries by the import gdal statement in my python program.

The GDAL is designed to run in Mac OS X Terminals, but the installation include python libraries which are not automatically linked to the program. Therefore, the only thing we need to do to make it work in python is to link those libraries properly. Python search libraries in predefined search path list. The list can be printed by executing the following code snippet in Python.

import sys
print sys.path

Note that this path list is different from the $PATH environment variable.

Edit PYTHONPATH Temporarily

One way to link GDAL’s python library is by editing the python search path in the .py file you are working with. The code looks like this:

import sys
sys.path.append("/path/to/gdal/libraries")
from osgeo import gdal

Note this approach only add the GDAL library directory to the PYTHONPATH temporarily, meaning if you close the program, the GDAL path will disappear. So you need to add this block of code every time when you want to use GDAL python library.

Edit PYTHONPATH Permanently

If you don’t want to edit PYTHONPATH every single time, there is another way to link GDAL libraries. Specifically, you can add GDAL library path to the PYTHONPATH by entering the following block of code in a Command Line Interface (e.g Terminal on Mac) from a Linux OS:

export PYTHONPATH="${PYTHONPATH}:/path/to/gdal/libraries" >> ~/.bash_profile
source ~/.bash_profile

The path to your GDAL library might be /Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages if you installed your GDAL library from kyngchaos.com.