I'm having issues getting off the ground with running PyQGIS on my OS X. I'm frankly very confused as some errors occur sporadically while executing the same code.

When I try the following:

QgsApplication.setPrefixPath('/Applications/QGIS.app/Contents/MacOS', True)

I either get one of three scenarios:

  • Segmentation fault: 11 when returning the list
  • A blank list returned
  • Or a this error after initQgis()...

    QCoreApplication::applicationDirPath: Please instantiate the QApplication object first QWidget: Must construct a QApplication before a QPaintDevice

A workaround I found to work is to instantiate a QgsApplication object first as the error suggests with something like

app = QgsApplication([], True)

However, the problem here is that this creates a GUI which I don't need - I'm just trying to do some scripting. If I change the instantiation parameter to False, then I get an error with initQgis() of:

QWidget: Cannot create a QWidget when no GUI is being used

Also, in a lot of examples I've found online you don't need the instantiation step... is there something funky with my setup?

I'm using a venv if that makes any difference... all commands I want to run work normally in the QGIS Python console, it's just the external script that's giving me issues.

Any thoughts?

Python: 2.7.10, QGIS: 2.10.1-Pisa, OS X: 10.10.3

2 Answers 2


I had also some troubles with this, here is my solution for OSX 10.9.5:

import os, sys
from qgis.core import *

app = QgsApplication([],True)
QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/MacOS", True)

layer = QgsVectorLayer('/tmp/myshape.shp', 'test', 'ogr')
print layer.isValid()

You need to add first Applications/Qgis.app/Contents/Resources/python to the PYTHONPATH

First solution outside Python

export PYTHONPATH=/Applications/Qgis.app/Contents/Resources/python
# then 
#Import QGIS
from qgis.core import *

Second solution in Python

import os, sys
#Import QGIS
from qgis.core import *

In both cases you need to initialize the app (otherwise crash)

app = QgsApplication([],True)
QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/Plugins", True)

You can now use PyQGIS

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

In the same way you can add the path of the plugins to sys, use the processing algorithms and...

  • export PYTHONPATH=/Applications/Qgis.app/Contents/Resources/Python should be python with lowercase p in Python
    – Master Bee
    Commented Nov 11, 2015 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.