More

Seg Faults and Instantiation Errors while running PyQGIS on OS X

Seg Faults and Instantiation Errors while running PyQGIS on OS X


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) QgsApplication.initQgis() QgsProviderRegistry.instance().providerList()

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


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

import os, sys sys.path.append('/Applications/QGis.app/Contents/Resources/python') from qgis.core import * app = QgsApplication([],True) QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/MacOS", True) QgsApplication.initQgis() layer = QgsVectorLayer('/tmp/myshape.shp', 'test', 'ogr') print layer.isValid()

You need to add firstApplications/Qgis.app/Contents/Resources/pythonto the PYTHONPATH

First solution outside Python

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

Second solution in Python

import os, sys sys.path.append('/Applications/QGis.app/Contents/Resources/python') #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) QgsApplication.initQgis()

You can now use PyQGIS

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

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


Watch the video: Python Add Interactivity to Jupyter Notebooks with ipywidgets