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.

asked Nov 27, 2018 at 13:22
0

1 Answer 1

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.

answered Jun 6, 2019 at 10:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.