3

This might be a dumb question, but I wasn't able to find the answer anywhere.

Reading the metadata of a raster file in Python using GDAL is as easy as:

result = str(gdal.Info(raster.tif))
print result

In this case I want to do the same for a shapefile. I know I can use ogrinfo -ro -so -al foo.shp in the shell, but I have not found a way to do the same only in Python within a single line.

I'm looking for something like:

result = str(ogr.Info(shapefile.shp))
print result

Am I missing something obvious or is there really no function like this?

  • try something from pcjericks.github.io/py-gdalogr-cookbook/… – Ian Turton Apr 25 '18 at 16:42
  • Already did that, but those only return specific information like feature count, extent, layer definition and so on. Of course I could get everything I'm looking for with multiple calls and afterwards append everything to a string, but that's why I'm looking for a function like ogr.Info(shapefile.shp) – Iridium Apr 25 '18 at 16:48
  • 1
    Then it doesn't exist. Nothing shows up with dir(ogr) and I can't see anything in the docs. If you can hack a nice module from the cookbook recipes then it might be a nice thing to publish. You'd probably get some help... Start a project on gitlab today! – Spacedman Apr 25 '18 at 16:53
  • 1
    Well, then at least I have the peace of mind that I'm not blind. Was thinking the whole time that I was missing something quite basic. I currently don't have time at all to start a project, but will keep it in mind for future endeavours! – Iridium Apr 25 '18 at 16:59
  • 3
    Use Fiona or GeoPandas, based on ogr – gene Apr 25 '18 at 17:04
1

Here is a more convoluted way to call anything gdal-related, using the subprocess module :

from subprocess import Popen, PIPE

args = ['ogrinfo', '-ro', '-so', '-al', 'bacon.shp']
process = Popen(args, stdout=PIPE, stderr=PIPE)

stdout = process.communicate()[0].decode('utf-8').strip()
print(stdout)

This acts as a virtual shell of sorts, and prints out whatever the shell returns. Here's some documentation about subprocess. It might be a bit heavy for what you want to do, but I've found it very useful for some tasks I had to do which weren't do-able using the GDAL module.

(NB. The decode/strip part is there just so that the output looks nicer.)

  • Thanks, it works like a charm! Not the one-liner that I was looking for, but definetly more compact (and maybe useful in the future!) than calling every single attribute and slapping it together in a string. – Iridium Apr 26 '18 at 11:41

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.