[GIS] calling gdal_merge.py into another python script running GDAL processes

gdalgdal-mergepython

I want to use gdal_merge.py to merge a series of .tif files prior to clipping the merged file to a shapefile boundary, but want to do so as part of another larger script that will execute a number of other processes. I am a python/GDAL newbie and am not sure how to go about calling gdal_merge.py into another script.

I cannot merely run gdal_merge.py on its own as it is but one step in a script that will hopefully execute a number of processes. Any thoughts on the best way to do this?

Best Answer

The easiest way to do this is by importing the path where gdal_merge.py is located, in my case, /usr/bin/ -- substitute with the path to gdal_merge on your system, which, obviously, could be a Windows path too.

import sys
sys.path.append('/usr/bin/')
import gdal_merge as gm

You will now have to build up an array for sys.argv, as if you were calling gdal_merge directly, e.g.,

sys.argv = ['-o','outputfile.tiff','inputfile1.png', 'inputfile2.png', ....'inputfile10.png']
gm.main()

There is more information on this Stack Overflow post

There is also the __init__.py mechanism, but this requires the file you are importing to be in a sub-directory of wherever you are running your python file from.