QGIS Python Console – Creating Layers vs Stand-Alone Application

pyqgis

I am having trouble creating a QGIS vector layer in a stand-alone python script while exactly the same code works fine in python console inside QGIS. The following code results in a proper displayable layer when executed in the python console:

layer = QgsVectorLayer('/abs/path/buses.shp', 'buses', 'ogr')

However, the same line of code results in an invalid layer in a standalone app (other QGIS functionality seems to work fine):

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

QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/Resources/python", True)
QgsApplication.initQgis()

layer = QgsVectorLayer('/abs/path/buses.shp', 'buses', 'ogr')
if not layer.isValid():
    print "Layer failed to load: ", layer.lastError() # returns empty string

It seems to me that there is some problem with QGIS data providers in the stand-alone app. Is there a way to find out what exactly happens inside QgsVectorLayer() or get a list of active QGIS data providers?

I am using QGIS 1.8 on OSX 10.8.3 with python2.7 from macports.

Best Answer

Set your prefix path to /Applications/QGIS.app/Contents/MacOS.

You can list the providers available using the providerList method of the provider registry:

from qgis.core import *
QgsApplication.setPrefixPath("/Applications/QGIS.app/Contents/MacOS", True)
QgsApplication.initQgis()
providers = QgsProviderRegistry.instance().providerList()
for provider in providers:
    print provider

To show the current settings, use:

print QgsApplication.showSettings()

This should match what you see in the Log Messages window, General tab in QGIS. If not, adjust your environment accordingly.

Related Question