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.
2 Answers 2
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.
-
Yes, setting prefix path to /Applications/QGIS.app/Contents/MacOS solves the problem. Thank you!srk– srk2013年04月25日 13:53:17 +00:00Commented Apr 25, 2013 at 13:53
But you will encounter many problems because QGIS is made for/uses the standard Apple Python (in/usr/bin) in the Python console and in the Shell and not the MacPorts version, except if you have installed the QGIS version of MacPorts.
-
looks like setting prefix path to /Applications/QGIS.app/Contents/MacOS make the app work for both Apple and MacPorts but python versions is something to keep in mind for future troubleshootingsrk– srk2013年04月25日 14:01:58 +00:00Commented Apr 25, 2013 at 14:01
/Applications/QGIS.app/Contents