GDAL/OGR概述
目录
Date: 2015-08-13 9:39
Summary: 一段代码一个小功能,简单清晰又实用。翻译自英文的cookbook。Thanks the author for sharing us such a wonderful tutorial!!!
GDAL/OGR概述
检查是否已经安装了GDAL/OGR
导入Python的GDAL模块,如果找不到的话就退出程序
import sys
try:
from osgeo import ogr, osr, gdal
except:
sys.exit('ERROR: cannot find GDAL/OGR modules')
检查GDAL/OGR的版本
下面这段代码检查导入GDAL/OGR模块的版本
import sys
from osgeo import gdal
version_num = int(gdal.VersionInfo('VERSION_NUM'))
if version_num < 1100000:
sys.exit('ERROR: Python bindings of GDAL 1.10 or later required')
启用Python异常
在默认情况下,GDAL/OGR的Python绑定在出现错误的时候不会引发异常。它们只会返回一个None的错误值并且向标准输出sys.stdout写一条错误信息。你可以通过调用UseException()函数启用异常。
from osgeo import gdal
# Enable GDAL/OGR exceptions
gdal.UseExceptions()
# open dataset that does not exist
ds = gdal.Open('test.tif')
# results in python RuntimeError exception that
# `test.tif' does not exist in the file system
你可以随时停止使用GDAL/OGR异常。
from osgeo import gdal
gdal.DontUseExceptions()
注册GDAL/OGR错误处理函数
下面这段代码注册了一个GDAL错误处理函数,该函数能抓取GDAL错误,类和信息。只有1.10版本以上才能使用。
try:
from osgeo import ogr, osr, gdal
except:
sys.exit('ERROR: cannot find GDAL/OGR modules')
# example GDAL error handler function
def gdal_error_handler(err_class, err_num, err_msg):
errtype = {
gdal.CE_None:'None',
gdal.CE_Debug:'Debug',
gdal.CE_Warning:'Warning',
gdal.CE_Failure:'Failure',
gdal.CE_Fatal:'Fatal'
}
err_msg = err_msg.replace('\n',' ')
err_class = errtype.get(err_class, 'None')
print 'Error Number: %s' % (err_num)
print 'Error Type: %s' % (err_class)
print 'Error Message: %s' % (err_msg)
if __name__=='__main__':
# install error handler
gdal.PushErrorHandler(gdal_error_handler)
# Raise a dummy error
gdal.Error(1, 2, 'test error')
#uninstall error handler
gdal.PopErrorHandler()
注:英文原版地址如下:https://pcjericks.github.io/py-gdalogr-cookbook/gdal_general.html
转载自:https://blog.csdn.net/weixin_34120274/article/details/87406396