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

QgsApplication.setPrefixPath("/Applications/QGIS.app/", True)
qgs = QgsApplication([], False)

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


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 Answer 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.