I have written several complicated python scripts that end up using ogr2ogr to load or translate data. I have been converting these scripts to standalone exe files meaning the team do not require Python installed and some of the additional modules I use in other parts of the code.

However, I always end up using a subprocess and calling shp2pgsql.exe or ogr2ogr.exe, like this

load_ogr = """ogr2ogr --config PG_USE_COPY YES -a_srs "EPSG:27700" -skipfailures -gt 65536 -f PGDump /vsistdout/ %s -lco GEOMETRY_NAME=geom -lco SCHEMA=data -lco CREATE_SCHEMA=OFF -lco CREATE_TABLE=OFF -lco SPATIAL_INDEX=OFF -nln %s | psql -d multi -U postgres -f -"""%(shapefilename,tablename)

run = subprocess.Popen(load_ogr, shell=True)


Which iterates through a file list and loads the data in.

However, I can not bundle this code effectively into a standalone exe because it calls ogr2ogr found via it being installed on the host machine and found in the PATH

How can I change this to use the python ogr bindings (ogr.py)?

I have found very little code examples or tutorials on how to use the python ogr version, so any pointers to good resources would be very useful too

  1. Begin with Chris Garrard's Geoprocessing with Python using Open Source GIS that will give you the foundations.
  2. after, when you know what you want to do, search on StackExchange, Gis StackExchange or on the Net. There are numerous applications, and not only in English (the scripts are universals) !
  3. and ogr2ogr exists in Python: ogr2ogr.py
| improve this answer | |

This took me quite a bit of time to figure out but with the help of this link

Using ogr2ogr to convert GML to shapefile in Python?

I was able to compose the correct ogr2ogr command which used the ogr2ogr.py which I imported at the top of my python script.

So an example of the call you use is:

ogr2ogr.main(["","-f", "KML", "out.kml", "data/san_andres_y_providencia_administrative.shp"])

However, you cannot substitute any of these for %s to use something like

filename = "Building.shp"

ogr2ogr.main(["","-f", "KML", "out.kml", %s])%(filename)

So instead you have to build up the sequence (ogr2ogr expects a sequence) and then pass that to ogr2ogr.main

For example

filename = "Building.shp"
format = "KML"
var1 = "-f"
output = "Output.kml"

seq = []

seq.append("") #this is required as ogr2ogr.py expects the first variable to be a python script


it is probably not the prettiest or pythonic solution but it does work.

| improve this answer | |

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.