質問

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