Date: 2015-08-13 9:39
Summary: 一段代碼一個(gè)小功能绩社,簡單清晰又實(shí)用摔蓝。翻譯自英文的cookbook。Thanks the author for sharing us such a wonderful tutorialS浒摇V尽!
GDAL/OGR概述
檢查是否已經(jīng)安裝了GDAL/OGR
導(dǎo)入Python的GDAL模塊劲阎,如果找不到的話就退出程序
import sys
try:
from osgeo import ogr, osr, gdal
except:
sys.exit('ERROR: cannot find GDAL/OGR modules')
檢查GDAL/OGR的版本
下面這段代碼檢查導(dǎo)入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異常
在默認(rèn)情況下绘盟,GDAL/OGR的Python綁定在出現(xiàn)錯(cuò)誤的時(shí)候不會(huì)引發(fā)異常鸠真。它們只會(huì)返回一個(gè)None的錯(cuò)誤值并且向標(biāo)準(zhǔn)輸出sys.stdout寫一條錯(cuò)誤信息悯仙。你可以通過調(diào)用UseException()函數(shù)啟用異常。
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
你可以隨時(shí)停止使用GDAL/OGR異常吠卷。
from osgeo import gdal
gdal.DontUseExceptions()
注冊GDAL/OGR錯(cuò)誤處理函數(shù)
下面這段代碼注冊了一個(gè)GDAL錯(cuò)誤處理函數(shù)锡垄,該函數(shù)能抓取GDAL錯(cuò)誤,類和信息祭隔。只有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