1

My question concerns OGR in Python3 on Windows. So I've installed gdal from the wheel file, and I started playing with OGR functions, but there's a problem I'm encountering that I can't understand. If GetFeatureCount() is called on a layer that was opened in a separate file Python stops working, but not if all my code is in the same script (reading & get count of features).

The code below works:

from osgeo import ogr

filename = '<path>'
driver = ogr.GetDriverByName("ESRI Shapefile")
datasource = driver.Open(filename)
layer = datasource.GetLayer()
print('Features count:', layer.GetFeatureCount())

But if I move the opening of the shapefile's layer to a separate file, it doesn't work anymore (Python stops working somehow):

class IO:
    @staticmethod
    def read_vector(filename):
        # load vector
        driver = ogr.GetDriverByName("ESRI Shapefile")
        datasource = driver.Open(filename)
        layer = datasource.GetLayer()

        return layer

And it called from this file:

from gdal_io import IO


filename =  '<path>'
layer = IO.read_vector(filename)
print('Features count:', layer.GetFeatureCount())

Is something necessary after reading the shapefile vector with OGR?

1 Answer 1

3

You have been bitten by a well known GDAL/OGR Python "gotcha".

Issue: Your datasource reference has gone out of scope (it's only referenced in the static method) and has orphaned your layer object which causes a crash.

Note: This isn't because you've opened the datasource from a class in an imported module, you could reproduce by simply defining a function in your main script that opens a datasource, gets a layer and returns the layer only. Or even by using something like layer = ogr.Open(filename).GetLayer(). Either way, the datasource gets dereferenced and python will crash if you try to use the orphaned layer object.

Solution: Return the datasource not the layer. Or use fiona, a much more pythonic interface to OGR.

0

Your Answer

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

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