1
from subprocess import PIPE, CalledProcessError, Popen
import subprocess
import osgeo 

raster = '/home/rphillips/Desktop/tif_dir/merged.tif'
raster_dir = os.path.dirname(raster) 
binary = raster_dir + 'binary.tif'
calc_list = []
calc_list = 'gdal_calc.py -A {} --outfile={} --NoDataValue=-9999 --calc "1 * (A != -9999)"'.format(raster,binary)
calc_for_subprocess = calc_list.split() 
print calc_for_subprocess

try:
    df = Popen(calc_for_subprocess, stdout=PIPE)
    output, err = df.communicate()
    print output
    print err
except CalledProcessError as e:
    print (e.message)
except Exception as E:
    print (E.message)

-----------output-----------------
['gdal_calc.py', '-A', '/home/rphillips/Desktop/tif_dir/merged.tif', '--outfile=/home/rphillips/Desktop/tif_dirbinary.tif', '--NoDataValue=-9999', '--calc', '"1', '*', '(A', '!=', '-9999)"']          

None

I ran the same variable calc_for_subprocess in BASH Terminal;

rphillips@OL100314:~$ gdal_calc.py -A /home/rphillips/Desktop/tif_dir/merged.tif --outfile=/home/rphillips/Desktop/tif_dir/binary.tif --NoDataValue=-9999 --calc "1 * (A != -9999)"
/usr/bin/gdal_calc.py:266: FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.
myNDVs=1*numpy.logical_or(myNDVs==1, myval==myNDV[i])
0 .. 10 .. 20 .. 30 .. 40 .. 50 .. 60 .. 70 .. 80 .. 90 .. 100 - Done

The terminal command created the raster that I needed.

However I'm confused why if the numpy syntax was an issue in the Py script (shown in BASH) why wasn't the list in the Python Script even passed through the Popen constructor? The output variable is empty.

I've had a look at the Python documentation on the subprocess module and had no luck finding anything that helped. Python 2.7.15 subprocess module documentation

On a side note: I think this reference explains the BASH gdal FutureError:- FutureWarning: comparison to None

Update: I have also tried putting the simple string calc_list when calling the Popen constructor and had the same outcome as above.

df = popen(calc_list, stdout=PIPE)

also tried this, with no luck;

subprocess.call(calc_for_subprocess,shell=True)

but this worked but gave me a weird raster, pixel values do not correspond to numpy expression;

subprocess.call(calc_list,shell=True)

  • Can you try it with the original string? df = Popen(calc_list, stdout=PIPE) – Marc Pfister Dec 22 '18 at 15:12
  • @MarcPfister cheers for the suggestion! I had failed to mention I had tried that option. Had same outcome unfortunately. Updated the question to incorporate this. – Rose Dec 22 '18 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.