Monday, 1 February 2016

python - Use subprocess.call with gdalwarp


I am now want to use subprocess.call with gdalwarp to clip raster from shapefile (in qgis 1.8.0)


I use raster→projections→wrap(reproject)to generate command_line below


gdalwarp -t_srs "+proj=tmerc +lat_0=0 +lon_0=121 +k=0.9999 +x_0=250000 +y_0=0
+ellps=GRS80 +units=m +no_defs" -dstnodata 0 -q -cutline "C:/Program Files

(x86)/Quantum GIS Wroclaw/test/area.shp"
-dstalpha -of GTiff C:/Program Files
(x86)/Quantum GIS Wroclaw/test/wrapM_0.tif "C:/Program Files
(x86)/Quantum GIS Wroclaw/test/wrap"

and following is my code


import gdal
from subprocess import call



crs='"+proj=tmerc +lat_0=0 +lon_0=121 +k=0.9999 +x_0=250000 +y_0=0
+ellps=GRS80 +units=m +no_defs"'

mask='"C:/Program Files(x86)/Quantum GIS Wroclaw/test/area.shp"'
input='C:/Program Files(x86)/Quantum GIS Wroclaw/test/wrapM_0.tif'
output='"C:/Program Files(x86)/Quantum GIS Wroclaw/test/wrap"'

call(gdalwarp, -t_srs crs -dstnodata 0 -q -cutline msak -dstalpha -of GTiff
input output)


And Python will give the error below:


  File "", line 1
call(gdalwarp, -t_srs crs -dstnodata 0 -q -cutline msak -dstalpha -of
GTiff input output)
^
SyntaxError: invalid syntax

How to fix the error here??



Answer



You have to specifiy the path to gdalwarp (in the example below I took: "C:\python32\python.exe", but you have to change it to your intallation path) and change your call function like that:



call(['C:\Program Files\GDAL\gdalwarp.exe', '-t_srs ' + crs, '-dstnodata 0', '-q', '-cutline ' + mask, '-dstalpha', '-of GTIFF', input, output]).

or:


call('C:\Program Files\GDAL\gdalwarp.exe -t_srs ' + crs + ' -dstnodata 0 -q -cutline ' + mask + ' -dstalpha -of GTIFF ' + input + ' ' + output, shell=True)

Another possibility is to use the popen function of the subprocess modul. And don't forget to add double quotes for the input variable, since you use a directory that contains blanks.


Have a look at the 2nd answer: How to call gdal_translate from Python code?


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...