1

One of the related questions mentions an issue with import order, but I don't think that applies here because this is a command-line script: I'm not using Qt, only QGIS libraries.

I'm trying to run the following:

import sys
from qgis.core import QgsApplication, QgsVectorLayer

sys.path.append("/Applications/QGIS.app/Contents/Resources/python")
QgsApplication.setPrefixPath("/Applications/QGIS.app/", True)
qgs = QgsApplication([], False)
qgs.initQgis()

layer = QgsVectorLayer("/path/to/file.shp", "layer", "ogr")
layer.isValid()  # False
for field in layer.fields():
    print field  # Nothing prints

qgs.exitQgis()

Assuming the path exists and points to a valid ESRI shapefile, any ideas as to why this fails to load correctly? Does it need to be explicitly loaded into the QgsApplication context? Is there something else I'm missing?

Environment: macOS Mojave, QGIS 2.18, Python 2.7.

1

I hope you have an answer to this by now, but just in case not I would suggest adding a line after the imports that sets the prefix path. It should look something like os.environ['QGIS_PREFIX_PATH'] = r'C:\OSGeo4W64\apps\qgis'. The code here is for Windows, but it should be similar in macOS. This worked for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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