GDAL Python 学习笔记-1

GDAL Python 学习笔记-1

Python GDAL/OGR Cookbook

基本

判断GDAL/OGR是否已安装

import sys
try:
from osgeo import ogr,osr,gdal
except:
sys.exit("Error: can not found ogr/osr/gdal modules")

查看安装的GDAL/OGR的版本

version = int(gdal.VersionInfo('VERSION_NUM')) #'VERSION_NUM'可以不写,但不能写成'VERSION'
print(version) # 2010000
if(version<1100000):
sys.exit("Error: Python bindings of GDAL 1.10 or later required")

启用Python异常

GDAL/OGR Python包在发生错误时,默认不会抛出异常,而是返回一个错误值,并将错误信息通过sys.stdout() 输出。通过使用gdal.UseExceptions()方法来启用异常

ds = gdal.Open("a.tif") # a.tif是随便写的一个文件,并不存在
# 不启用异常时
ERROR 4: `a.tif' does not exist in the file system,
and is not recognized as a supported dataset name.
# 使用了 gdal.UseExceptions() 时
Traceback (most recent call last):
File "F:/workspace/python/gdal/readTif.py", line 13, in <module>
ds = gdal.Open("a.tif")
RuntimeError: `a.tif' does not exist in the file system,
and is not recognized as a supported dataset name.

当然,也可以随时停用:gdal.DontUseExceptions()

安装GDAL/OGR 错误处理器 | error handler

一个捕获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()
文章目录
  1. 1. GDAL Python 学习笔记-1
    1. 1.1. 基本
      1. 1.1.1. 判断GDAL/OGR是否已安装
      2. 1.1.2. 查看安装的GDAL/OGR的版本
      3. 1.1.3. 启用Python异常
      4. 1.1.4. 安装GDAL/OGR 错误处理器 | error handler
|