Python – How to Call FWTools (ogr2ogr) from ArcGIS Python Script

ogrpython

In ArcGIS, I want to use a Python script (and a standard ArcGIS script tool UI) to call functionality from FWTools.

How would I make the call to FWTools? I tried using os.system(C:\WINDOWS\system32\cmd.exe /K "C:\Program Files\FWTools2.4.7\setfw.bat") which is what the windows shortcut calls, but that is not it. It seems I am probably missing something rather simple, but I can't figure out how to make the right call through python to get FWTools & ogr2ogr operating on the string I pass.

My UI looks like this:

enter image description here

and the pseudo-code behind it is something like:

'ogr2ogr -f "' + outformat + '" "' + outfile + '" "' + infile + '" ' + ogrvars

Best Answer

I did this a while ago, I'm not sure it is the best way to go, but it worked at the time.

g.fwtools = r"D:\FWTools2.2.8"
# name of translate command
g.cmd = os.path.join(g.fwtools, "bin", "gdal_translate.exe")


def setupfwtools(g):
    """
    Sets the environment variables to access the GDAL tools.
    This allows us to run this script without depending on the
    use running the FW Tools seup batch file first.
    """
    os.environ['FWTOOLS_DIR']=g.fwtools
    os.environ['PATH']=g.fwtools+'\\bin;'+g.fwtools+'\\python;'+os.environ['PATH']
    os.environ['PYTHONPATH']=g.fwtools+'\\pymod'
    os.environ['PROJ_LIB']=g.fwtools+'\\proj_lib'
    os.environ['GEOTIFF_CSV']=g.fwtools+'\\data'
    os.environ['GDAL_DATA']=g.fwtools+'\\data'
    os.environ['GDAL_DRIVER_PATH']=g.fwtools+'\\gdal_plugins'

args = [g.cmd] + [option1 option2]
args.append(infile)
args.append(outfile)
os.spawnve(os.P_WAIT, args[0], args, os.environ)
Related Question