In my Python script I call a GDAL utility using:
subprocess.call('gdal_rasterize -a ICE_TYPE -where \"ICE_TYPE=\'Open Water\'\" -b 1 -burn 5 -l ' + shapefileshortname +' ' + shapefile + ' ' + outraster)
or
os.system('gdal_rasterize -a ICE_TYPE -where \"ICE_TYPE=\'Open Water\'\" -b 1 -burn 5 -l ' + shapefileshortname +' ' + shapefile + ' ' + outraster)
Now gdal_rasterize gives an error for a corrupt shapefile, but using "try-except" on os.system only works for errors related to os.system itself.
Is there within the Python script a way to handle errors by a command line function called via os.system or subprocess.call ?
3 Answers 3
Try this out, if the exit status is 0 then the command has run as expected.
program = "C:\Path\to\GDAL"
command = 'gdal_rasterize -a ICE_TYPE -where \"ICE_TYPE=\'Open Water\'\" -b 1 -burn 5 -l ' + shapefileshortname +' ' + shapefile + ' ' + outraster
input_command = [command]
command_run = subprocess.call([program, input_command])
if command_run == 0:
print "Its worked!!"
else:
print "There was a problem, so do something else"
-
with your version I get an "Windows Error 5: Access is denied" But it works with command_run = subprocess.call('gdal_rasterize -a ICE_TYPE -where \"ICE_TYPE=\'Open Water\.... ) and then checking the value of "command_run" like you doMax– Max2014年02月17日 07:38:08 +00:00Commented Feb 17, 2014 at 7:38
-
PS: now I realize it works "kind of" since the error code is given back and my Python script continues now. However, the issue is that gdal_rasterize crashes and won't be restarted in the next loop of the Python code -- how to do that is a different issue...Max– Max2014年02月19日 07:14:40 +00:00Commented Feb 19, 2014 at 7:14
subprocess.check_output can catch anything gdal_rasterize might write to stdout or stderr. That's as good as you'll be able to do. http://docs.python.org/2/library/subprocess.html#subprocess.check_output
subprocess.call
returns 0, in case of success, and 1 in case of failure. You can use subprocess.Popen
instead.
res = subprocess.Popen('gdal_rasterize -a ICE_TYPE -where \"ICE_TYPE=\'Open Water\'\" -b 1 -burn 5 -l ' + shapefileshortname +' ' + shapefile + ' ' + outraster, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
# Wait for the process end and print error in case of failure
if res.wait() != 0:
output, error = res.communicate()
print error
This is discussed also in stackoverflow: https://stackoverflow.com/questions/29580663/save-error-message-of-subprocess-command