Python – Calling gdal_merge in a Script

demgdal-mergepythonspyderwindows

I am new to python and breaking my head on how to use gdal_merge in a (spyder) python script. I use Windows 10, Python 3.6 and have the gdal tool installed from osgeo4w. I realize many other posts describe this problem but none could help me resolving this issue.

When i call the gdal module from cmd, it works like a charm:

 python "C:\OSGeo4W64\bin\gdal_merge.py" -o merged.tif input1.tif input2.tif

However, I cannot get it working properly in a python script (spyder).

A first approach produces an output but not with the right name: it produces an 'out.tif' file and not the 'merged.tif' file as I request:

import sys
sys.path.append('C:\\OSGeo4W64\\bin')
import gdal_merge as gm
gm.main(['-o', 'merged.tif', 'N00W078.tif', 'N00W079.tif'])

A second approach simply produces no output:

import subprocess
merge_command = ["python", "C:\OSGeo4W64\bin\gdal_merge.py", "-o", "merged.tif", "input1.tif", "input2.tif"]
subprocess.call(merge_command,shell=True)

Any thoughts on how to resolve this issue?

Best Answer

Add an empty argument in the first approach (because gdal_merge.py parses arguments starting from 1 and not 0):

import sys
sys.path.append('C:\\OSGeo4W64\\bin')
import gdal_merge as gm
gm.main(['', '-o', 'merged.tif', 'N00W078.tif', 'N00W079.tif'])

Join the path of gdal_merge.py in the second approach:

import os, subprocess
gm = os.path.join('C:\\','OSGeo4W64','bin','gdal_merge.py')
merge_command = ["python", gm, "-o", "merged.tif", "input1.tif", "input2.tif"]
subprocess.call(merge_command,shell=True)
Related Question