Thursday, 15 September 2016

pyqgis - Getting dataProvider from vector layer outside QGIS


I'm using PyScripter to explore PyQGIS API because of it's very handy auto-completion function.


I've managed to get a handle on a PostGis vector layer by:


>>> from qgis.core import *
>>> uri = QgsDataSourceURI()
>>> uri.setConnection("","5432","","","")
>>> uri.setDataSource("public","","")

>>> vLayer=QgsVectorLayer(uri.uri(),"","postgres")
>>> vLayer


So far so good. My next step is to explore the layer's dataProvider.


>>> vLayer.dataProvider()
>>>

Why doesn't vLayer.dataProvider() yield anything, like in QGIS Python Console?


Do I need to initialize vLayer more?




Answer



You haven't setup your QGIS Python environment correctly.


At the start of your script you need to put these four lines in order to tell the QGIS libs where to look for providers.


qgishome = 'C:\OSGeo4W\apps\qgis-dev\'
app = QgsApplication([], True)
QgsApplication.setPrefixPath(qgishome, True)
QgsApplication.initQgis()

when you need to exit the QGIS session you should use:


QgsApplication.exitQgis()


I have a growing simple set of examples at https://github.com/NathanW2/pyqgis-playground which can help to understand the basics of getting something setup. See the canvas example


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...

Blog Archive