Search code examples
pythonpython-2.7argumentssubprocessgdal

How to correctly use gdaladdo in a Python program?


My question is about a GDAL (Geospatial Data Abstraction Library) tool named gdaladdo. This tool is supposed to build overview images from a .tif file. From the documentation I've found on it, I can see that it is usually typed into a command prompt. I've been trying to find a way to have it run via my Python program because I have a few thousand .tif images that need external overviews. My ultimate goal with this program is to be able to pass it the .tif image and for it to create an .rrd pyramid for it. Here's my code so far:

import gdal
import os
from subprocess import call

#Define gdaladdo
gdaladdoFile = 'C:\Program Files (x86)\GDAL\gdaladdo.exe'

#--------------------------------------------------------

os.chdir("Images")

openfile = open('imagenames.txt', 'r')

if {openfile.closed == False}:
    count = 0
    while count < 5:
        #Grab the image to work with
        filename = openfile.readline()

        #Strip off the newline
        filename.rstrip('\n')

        #Create pyramid
        call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16'])
        count += 1
    openfile.close()

else:
    print "No file to open!"

I get errors pertaining to the call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16']) line. When normally typing this command into the command prompt, it should look like this: 'gdaladdo -ro --config COMPRESS_OVERVIEW DEFLATE erdas.img 2 4 8 16' but Python says the options (like --config USE_RRD YES) are incorrect syntax. So I followed an example of passing arguments to a subprocess (that I found on here) and put the options inside single quotes and added commas after each one. The syntax errors disappear but new ones crop up when I run the program to test it. It says " FAILURE: Unknown option name '--config USE_RRD YES' " in the command prompt window. How should I change this particular line to make it do what I want it to do?

I'm new to stackoverflow and still studying programming in college so please forgive my ignorance and be gentle with me. Thank you in advance for your help with this problem.

gdaladdo reference link, in case it is needed.


Solution

  • Changing the line of code from this:

    call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16'])
    

    To this:

    call([gdaladdoFile, '-ro', '--config', 'USE_RRD', 'YES', filename, '2 4 8 16'])
    

    Solved my issue!