5

Im trying to iterate over features in a vector layer following Iterating over Vector Layer:

from qgis.core import *
import qgis.utils
from qgis.core import QgsVectorLayer

shapefile = '/media/bera/Lagring/GIS/data/ok_riks_Sweref_99_TM_shape/oversikt/riks/ak_riks.shp'

layer = QgsVectorLayer(shapefile, 'borders', 'ogr')
it = layer.getFeatures()

for feature in it:
    geom = feature.geometry()
    print geom.type()
    print 'test'

print 'stop'

It will not go into the for block so all that is printed out is stop

The objects are created:

layer
<qgis._core.QgsVectorLayer object at 0x7fa08d2bcb98>
it
<qgis._core.QgsFeatureIterator object at 0x7fa08d32e218>

What am i doing wrong?

2 Answers 2

5

Check that the layer is valid. If the layer, or the path is not valid qgis will no raise an error, it will return a QgsVectorLayer object where you can call the methods but with mostly no-op.

layer = QgsVectorLayer(shapefile, 'borders', 'ogr')
if not layer.isValid():
    raise Exception('Layer is not valid')

It will be probably a bad path. Also try to open (manually) the file in qgis to check if there is any error with the shp.

1
  • It was not valid
    – BERA
    Dec 3, 2017 at 15:14
3

From Using PyQGIS in standalone scripts i added:

QgsApplication.setPrefixPath("/home/bera/.qgis2/", True) #Path to qgis installation
qgs = QgsApplication([], False)
qgs.initQgis()

#Script goes here

qgs.exitQgis()

And now it is working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.