I am writing a Python script that uses 3rd party modules from GDAL. The GDAL functions do not raise exceptions when an error occurs, but do send messages to stdout. Generally, the errors that occur with GDAL functions do not warrant stopping the process and I don't need to know about the error having occurred.

Is there a way I can intercept the messages that are being sent to stdout before they are printed in the console? The GDAL messages interfere with the messages that I have provided in my own code.

有帮助吗?

解决方案

As described in "Python Gotchas", you can turn on Exceptions using gdal.UseExceptions(), e.g.:

from osgeo import gdal

dsrc = gdal.Open('nonexist')
# ... silence

gdal.UseExceptions()

dsrc = gdal.Open('nonexist')
# Traceback (most recent call last):
#   File "<interactive input>", line 1, in <module>
# RuntimeError: `nonexist' does not exist in the file system,
# and is not recognised as a supported dataset name.

You could always then use a try except block get the actual error message string:

try:
    dsrc = gdal.Open('nonexist')
except RuntimeError as e:
    print(str(e))

which will print the error message:

`nonexist' does not exist in the file system, and is not recognised as a supported dataset name.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top