QGIS – Calling QGIS from MacOS Python

osxpythonqgis

I would like to import qgis.core and utils from my own copy of python. I do have PYQT4 installed there.

I'd be happy to add to my PYTHONPATH or sys.path.append in my code, where do the qgis modules live (on a Mac)?

Best Answer

if you use the Kyng Chaos version:

1) First solution with the PYTHONPATH variable:

Add qgis to the PYTHONPATH (terminal)

$ export PYTHONPATH=/Applications/Qgis.app/Contents/Resources/python

You can add this line to your .bash_profile

Then in Python

# Import qgis
from qgis.core import * 
QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS", True)
# init the application
QgsApplication.initQgis()

Then you can use PyQGIS

layer = QgsVectorLayer('/Users/Shared/test.shp', 'test', 'ogr')
layer.isValid()
True

2) second solution, all in Python (from Custom Initialization for running standalone PyQGIS processing.):

import os
import sys
sys.path.append('/Applications/QGis.app/Contents/Resources/python/')
sys.path.append('/Applications/QGis.app/Contents/Resources/python/plugins') # if you want to use the processing module, for example
from qgis.core import *
app = QgsApplication([],True)
QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/Plugins", True)
QgsApplication.initQgis()
import processing
....

If you use the Homebrew version , the PATHs are different (look at Homebrew-osgeo4mac)

Related Question