1

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
Tristan Forward
  • 2,199
  • 3
  • 23
  • 43
  • 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

3 Answers3

3

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

from qgis.core import QgsApplication
QgsApplication.initQgis()
... your stuff here
Nathan W
  • 34,706
  • 5
  • 97
  • 148
2

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()
MonsterMushroom
  • 524
  • 4
  • 19
1

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.

Tristan Forward
  • 2,199
  • 3
  • 23
  • 43