0

Within PyCharm

import qgis.core as qgis
vector_lyr = qgis.QgsVectorLayer("Point", "distance nodes", "memory")
pr = vector_lyr.dataProvider()
print pr
prints None

Within Python Interpreter in QGIS

import qgis.core as qgis
vector_lyr = qgis.QgsVectorLayer("Point", "distance nodes", "memory")
pr = vector_lyr.dataProvider()
print pr
prints <qgis.core.QgsVectorDataProvider object at 0x000000000DAFF0D0>

I've tried this Getting dataProvider from vector layer outside QGIS and still no luck. Thanks.

[Edit] I found this: Access Sextante (processing) in standalone QGIS app? is this the case for dataProviders? Is there a workaround?

[EDIT2]

Tried this to no avail. I'm trying to create an in memory vector layer, write values to it then do something else after.

import qgis.core as qgis

qgis.QgsApplication.initQgis()

vector_lyr = qgis.QgsVectorLayer("Point", "distance nodes", "memory")
pr = vector_lyr.dataProvider()
print pr
prints None
  • You need to do a few things before you can access layers. One of the main things it to initQGis with data providers – Nathan W May 21 '14 at 23:06
2

You need to first initQgis so that the data providers are loaded:

from qgis.core import QgsApplication
QgsApplication.initQgis()
... your stuff here
0

I was able to get it to work by following what Nathan W said (thank you Nathan) about adding this code:

QgsApplication.initQgis(). 

As well as having to set:

qgishome = r'C:\OSGeo4W64\apps\qgis-dev\\' to r'C:\OSGeo4W64\apps\qgis\\'.

This bit of code was useful for debugging.

QgsApplication.initQgis()

providers = QgsProviderRegistry.instance().providerList()
for provider in providers:
    print provider

print QgsApplication.showSettings()

When ran on qgis-dev it had only one provider. While qgis path had many more, so I stuck this the one that had more.

I then had to set an windows environment variable for GDAL_DATA to

"C:\OSGeo4W64\share\epsg_csv"

After restarting the interpreter everything was working as it should.

0

I believe the System has changed a bit since the answers of 2014. Only calling

QgsApplication.initQgis()

without first Setting up the QgsApplication can crash Python in the current Version (2.14 LTR). I was successful in using the following code at the top of my script:

qgs = QgsApplication(sys.argv, False)
qgs.setPrefixPath(r"C:\Program Files (x86)\QGIS 2.18\apps\qgis-ltr", True)
qgs.initQgis()
  • This does not work for the current LTR 2.18.23. – Blinxen Sep 10 '18 at 9:19

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.