Sunday, 2 September 2018

GDAL and Python - Don't print GDAL Error messages


According to the GDAL Python Documentation, GDAL functions do not raise exceptions or errors but do print errors to the console via stdout and stderr.


I have some code in my script that calls GetStatistics on a GDAL raster band. If the band only contains nodata cells (which is possible because it is a tile of a larger dataset) the GetStatistics call fails with an error, but the script continues. I would prefer not to see the error messages that are still printed to the console when this happens as it interferes with other print statements that I have written into my own script.


Is it possible to turn off these messages?



Answer



There are some python 'only' rules stated at the 'Python Gotchas' page.



At the beginning they state that:



By default, the GDAL and OGR Python bindings do not raise exceptions when errors occur. Instead they return an error value such as None and write an error message to sys.stdout.



So first enable the use of exceptions, by issuing gdal.UseExceptions() somewhere in the beginning of your script. And secondly catch if any exceptions and do whatever you want with them (including nothing)


gdal.UseExceptions()  # Enable errors
...
try:
band.GetStatisticsts()
except RuntimeError: # <- Check first what exception is being thrown

pass

If you're curious here's a link from python's wiki where they describe the methods of exception handling.


As far as I can tell, using gdal.UseExceptions() will normalize the behaviour of all the methods in the gdal lib, by making those methods to use the Python Exceptions. If you really want to ignore all exceptions put the problematic part of your code inside a try/except block eg.:


>>>
try:
print "1"
print "2"
a = 0
b = 1

c = b/a # <- I just divided by zero.
except:
print "Everything is ok" # <- but Everything is Ok.
# If you really want to be silent replace with pass
>>> 1
2
'Nothing to see here'

Just be careful, because that way when an exception happens, your script will silently break from the procedure without any indication of what went wrong.


Also I want to point a couple of things as well:




  1. If you're opt to go that way, you're responsible if your program does. You're choosing to turn a blind eye at any errors that come in your way.

  2. If you catch ALL the exceptions, you will also catch the 'KeyboardInterrupt' exception as well. No more ctrl-c (if you're inside a try/except block).

  3. Your code at some point is encountering a processing error. Since you're not using gdal.UseExceptions() you're experiencing that error as a sys.stdout response. Use a try/except block at that point to plug that hole.


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...