python gdal捕获出错信息ERROR

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/nima1994/article/details/81871124

问题描述

默认情况下,python gdal出错信息以字符串形式打印出去,返回对象None,python不能接收到出错异常。如下代码

from osgeo import gdal
# gdal.UseExceptions() #1
try:
    ds = gdal.Open('test.tif')
except Exception:
    print("error.")
print(ds)
print("finish.")

输出:

ERROR 4: test.tif: No such file or directory
None
finish.

多次运行发现ERROR 4出现的顺序不同,估计是多线程等的缘故。另见

解决方案

例1

去掉#1处代码的注释,则可以让程序正常抛出异常。输出如下:

error.
Traceback (most recent call last):
File “E:/Code/PycharmProjects/python_demo/test/vi1.py”, line 8, in
print(ds)
NameError: name ‘ds’ is not defined

例2

如下代码输出:

from osgeo import gdal
gdal.UseExceptions() #1
ds = gdal.Open('test.tif')

Traceback (most recent call last):
File “E:/Code/PycharmProjects/python_demo/test/vi1.py”, line 3, in
ds = gdal.Open(‘test.tif’)
File “D:\Anaconda3\lib\site-packages\osgeo\gdal.py”, line 2914, in Open
return _gdal.Open(*args)
RuntimeError: test.tif: No such file or directory

参考:http://pcjericks.github.io/py-gdalogr-cookbook/gdal_general.html

猜你喜欢

转载自blog.csdn.net/nima1994/article/details/81871124