General API

Configuration Management

osgeo.gdal.config_option(key, value, thread_local=True)

Temporarily define a configuration option.

Parameters:
  • key (str) -- Name of the configuration option

  • value (str) -- Value of the configuration option

  • thread_local (bool, default=True) -- Whether the configuration option should be only set on the current thread. Note that GDAL_CACHEMAX cannot be set with thread_local=True.

Returns:

A context manager

Return type:

contextlib.contextmanager

Examples

>>> with gdal.config_option("GDAL_NUM_THREADS", "ALL_CPUS"):
...     gdal.Warp("out.tif", "in.tif", dstSRS="EPSG:4326")
<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x...> >
osgeo.gdal.config_options(options, thread_local=True)

Temporarily define a set of configuration options.

Parameters:
  • options (dict) -- Dictionary of configuration options passed as key, value

  • thread_local (bool, default=True) -- Whether the configuration options should be only set on the current thread. Note that GDAL_CACHEMAX cannot be set with thread_local=True.

Returns:

A context manager

Return type:

contextlib.contextmanager

Examples

>>> with gdal.config_options({"GDAL_NUM_THREADS": "ALL_CPUS"}):
...     gdal.Warp("out.tif", "in.tif", dstSRS="EPSG:4326")
<osgeo.gdal.Dataset; proxy of <Swig Object of type 'GDALDatasetShadow *' at 0x...> >
osgeo.gdal.ClearCredentials(pszPathPrefix=None)
osgeo.gdal.ClearPathSpecificOptions(pszPathPrefix=None)
osgeo.gdal.GetCacheMax() GIntBig

Get the maximum size of the block cache. See GDALGetCacheMax().

Returns:

maximum cache size in bytes

Return type:

int

osgeo.gdal.GetCacheUsed() GIntBig

Get the number of bytes in used by the block cache. See GDALGetCacheUsed().

Returns:

cache size in bytes

Return type:

int

osgeo.gdal.GetConfigOption(pszKey, pszDefault=None) char const *

Return the value of a configuration option. See CPLGetConfigOption().

Parameters:
  • pszKey (str) -- name of the configuration option

  • pszDefault (str, optional) -- default value to return if the option has not been set

Return type:

str

osgeo.gdal.GetConfigOptions() char **

Return a dictionary of currently set configuration options. See CPLGetConfigOptions().

Return type:

dict

Examples

>>> with gdal.config_options({'A': '3', 'B': '4'}):
...     gdal.SetConfigOption('C', '5')
...     gdal.GetConfigOptions()
...
{'C': '5', 'A': '3', 'B': '4'}

See also

GetConfigOption(), GetGlobalConfigOptions()

osgeo.gdal.GetCredential(pszPathPrefix, pszKey, pszDefault=None) char const *
osgeo.gdal.GetGlobalConfigOption(pszKey, pszDefault=None) char const *

Return the value of a global (not thread-local) configuration option. See CPLGetGlobalConfigOption().

Parameters:
  • pszKey (str) -- name of the configuration option

  • pszDefault (str, optional) -- default value to return if the option has not been set

Return type:

str

osgeo.gdal.GetNumCPUs() int

Return the number of processors detected by GDAL.

Return type:

int

osgeo.gdal.GetPathSpecificOption(pszPathPrefix, pszKey, pszDefault=None) char const *
osgeo.gdal.GetThreadLocalConfigOption(pszKey, pszDefault=None) char const *

Return the value of a thread-local configuration option. See CPLGetThreadLocalConfigOption().

Parameters:
  • pszKey (str) -- name of the configuration option

  • pszDefault (str, optional) -- default value to return if the option has not been set

Return type:

str

osgeo.gdal.GetUsablePhysicalRAM() GIntBig
osgeo.gdal.HasThreadSupport() int
osgeo.gdal.SetCacheMax(nBytes)

Set the maximum size of the block cache. See GDALSetCacheMax().

Parameters:

nBytes (int) -- Cache size in bytes

See also

GDAL_CACHEMAX

osgeo.gdal.SetConfigOption(pszKey, pszValue)

Set the value of a configuration option for all threads. See CPLSetConfigOption().

Parameters:
  • pszKey (str) -- name of the configuration option

  • pszValue (str) -- value of the configuration option

osgeo.gdal.SetCredential(pszPathPrefix, pszKey, pszValue)
osgeo.gdal.SetPathSpecificOption(pszPathPrefix, pszKey, pszValue)
osgeo.gdal.SetThreadLocalConfigOption(pszKey, pszValue)

Set the value of a configuration option for the current thread. See CPLSetThreadLocalConfigOption().

Parameters:
  • pszKey (str) -- name of the configuration option

  • pszValue (str) -- value of the configuration option

osgeo.gdal.VersionInfo(request='VERSION_NUM') char const *

Data Type Information

osgeo.gdal.DataTypeIsComplex(eDataType) int
osgeo.gdal.DataTypeUnion(a, b) GDALDataType
osgeo.gdal.DataTypeUnionWithValue(a, val, isComplex) GDALDataType
osgeo.gdal.GetDataTypeByName(pszDataTypeName) GDALDataType

Return the data type for a given name.

Parameters:

pszDataTypeName (str) -- data type name

Returns:

data type code

Return type:

int

Examples

>>> gdal.GetDataTypeByName('Int16') == gdal.GDT_Int16
True
osgeo.gdal.GetDataTypeName(eDataType) char const *

Return the name of the data type.

Parameters:

eDataType (int) -- data type code

Return type:

str

Examples

>>> gdal.GetDataTypeName(gdal.GDT_Int16)
'Int16'
>>> gdal.GetDataTypeName(gdal.GDT_Float64)
'Float64'
osgeo.gdal.GetDataTypeSize(eDataType) int
osgeo.gdal.GetDataTypeSizeBits(eDataType) int
osgeo.gdal.GetDataTypeSizeBytes(eDataType) int

Error Handling

osgeo.gdal.ConfigurePythonLogging(logger_name='gdal', enable_debug=False)

Configure GDAL to use Python's logging framework

osgeo.gdal.Debug(msg_class, message)
osgeo.gdal.DontUseExceptions()

Disable exceptions in all GDAL related modules (osgeo.gdal, osgeo.ogr, osgeo.osr, osgeo.gnm). Note: prior to GDAL 3.7, this only affected the calling module

osgeo.gdal.Error(msg_class=CE_Failure, err_code=0, msg='error')
osgeo.gdal.ErrorReset()
class osgeo.gdal.ExceptionMgr(useExceptions=True)

Context manager to manage Python Exception state for GDAL/OGR/OSR/GNM.

Separate exception state is maintained for each module (gdal, ogr, etc), and this class appears independently in all of them. This is built in top of calls to the older UseExceptions()/DontUseExceptions() functions.

Example:

>>> print(gdal.GetUseExceptions())
0
>>> with gdal.ExceptionMgr():
...     # Exceptions are now in use
...     print(gdal.GetUseExceptions())
1
>>>
>>> # Exception state has now been restored
>>> print(gdal.GetUseExceptions())
0
osgeo.gdal.GetErrorCounter() unsigned int
osgeo.gdal.GetLastErrorMsg() char const *
osgeo.gdal.GetLastErrorNo() int
osgeo.gdal.GetLastErrorType() int
osgeo.gdal.GetUseExceptions() int
osgeo.gdal.PopErrorHandler()
osgeo.gdal.PushErrorHandler(pfnErrorHandler=0) CPLErr
osgeo.gdal.quiet_errors()

Temporarily install an error handler that silences all warnings and errors.

Returns:

A context manager

Return type:

contextlib.contextmanager

Examples

>>> with gdal.ExceptionMgr(useExceptions=False), gdal.quiet_errors():
...     gdal.Error(gdal.CE_Failure, gdal.CPLE_AppDefined, "you will never see me")
osgeo.gdal.quiet_warnings()

Temporarily install an error handler that silences all warnings.

Added in version 3.11.

Returns:

A context manager

Return type:

contextlib.contextmanager

Examples

>>> with gdal.ExceptionMgr(useExceptions=False), gdal.quiet_warnings():
...     gdal.Error(gdal.CE_Warning, gdal.CPLE_AppDefined, "you will never see me")
osgeo.gdal.SetCurrentErrorHandlerCatchDebug(bCatchDebug)
osgeo.gdal.SetErrorHandler(pfnErrorHandler=0) CPLErr
osgeo.gdal.UseExceptions()

Enable exceptions in all GDAL related modules (osgeo.gdal, osgeo.ogr, osgeo.osr, osgeo.gnm). Note: prior to GDAL 3.7, this only affected the calling module

File Management

osgeo.gdal_fsspec module

Module exposing GDAL Virtual File Systems (VSI) as a "gdalvsi" fsspec implementation.

Importing "osgeo.gdal_fsspec" requires the Python "fsspec" (https://filesystem-spec.readthedocs.io/en/latest/) module to be available.

A generic "gdalvsi" fsspec protocol is available. All GDAL VSI file names must be simply prefixed with "gdalvsi://". For example:

  • "gdalvsi://data/byte.tif" to access relative file "data/byte.tif"

  • "gdalvsi:///home/user/byte.tif" to access absolute file "/home/user/byte.tif"

  • "gdalvsi:///vsimem/byte.tif" (note the 3 slashes) to access VSIMem file "/vsimem/byte.tif"

  • "gdalvsi:///vsicurl/https://example.com/byte.tif (note the 3 slashes) to access "https://example.com/byte.tif" through /vsicurl/

since:

GDAL 3.11

class osgeo.gdal_fsspec.VSIFileSystem(*args, **kwargs)

Bases: AbstractFileSystem

Implementation of AbstractFileSystem for a GDAL Virtual File System

copy(path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs)

Implements AbstractFileSystem.copy()

info(path, **kwargs)

Implements AbstractFileSystem.info()

ls(path, detail=True, **kwargs)

Implements AbstractFileSystem.ls()

makedirs(path, exist_ok=False)

Implements AbstractFileSystem.makedirs()

mkdir(path, create_parents=True, **kwargs)

Implements AbstractFileSystem.mkdir()

modified(path)

Implements AbstractFileSystem.modified()

mv(path1, path2, recursive=False, maxdepth=None, **kwargs)

Implements AbstractFileSystem.mv()

rmdir(path)

Implements AbstractFileSystem.rmdir()

osgeo.gdal_fsspec.register_vsi_implementations()

Register a generic "gdalvsi" protocol. This method is automatically called on osgeo.gdal_fsspec import.

osgeo.gdal.VSIFile class

class osgeo.gdal.VSIFile(path, mode, encoding='utf-8', options={})

Class wrapping a GDAL VSILFILE instance as a Python BytesIO instance

Since:

GDAL 3.11

close()

Disable all I/O operations.

read(size=-1)

Read at most size bytes, returned as a bytes object.

If the size argument is negative, read until EOF is reached. Return an empty bytes object at EOF.

seek(offset, whence=0)

Change stream position.

Seek to byte offset pos relative to position indicated by whence:

  • 0: Start of stream (the default). pos should be >= 0;

  • 1: Current position - pos may be negative;

  • 2: End of stream - pos usually negative.

Returns the new absolute position.

tell()

Current file position, an integer.

write(x)

Write bytes to file.

Return the number of bytes written.

Low level functions

osgeo.gdal.CloseDir(dir)
osgeo.gdal.CopyFile(pszSource, pszTarget, fpSource=None, nSourceSize=-1, options=None, callback=0, callback_data=None) int
osgeo.gdal.CopyFileRestartable(pszSource, pszTarget, pszInputPayload, options=None, callback=0, callback_data=None)
class osgeo.gdal.DirEntry(*args)

Proxy of C++ DirEntry class.

IsDirectory(self) bool
property extra
property mode
property modeKnown
property mtime
property mtimeKnown
property name
property size
property sizeKnown
property thisown

The membership flag

osgeo.gdal.FileFromMemBuffer(path, nBytes) VSI_RETVAL
osgeo.gdal.FindFile(pszClass, path) char const *
osgeo.gdal.GetFileMetadata(path, domain, options=None) char **
osgeo.gdal.GetFileSystemOptions(path) char const *
osgeo.gdal.GetFileSystemsPrefixes() char **
osgeo.gdal.Mkdir(path, mode) VSI_RETVAL
osgeo.gdal.MkdirRecursive(path, mode) VSI_RETVAL
osgeo.gdal.Move(old_path, new_path, options=None, callback=0, callback_data=None) VSI_RETVAL
osgeo.gdal.MoveFile(pszSource, pszTarget) int
osgeo.gdal.OpenDir(path, nRecurseDepth=-1, options=None) VSIDIR *
osgeo.gdal.ReadDir(path, nMaxFiles=0) char **
osgeo.gdal.ReadDirRecursive(path) char **
osgeo.gdal.Rename(old_path, new_path) VSI_RETVAL
osgeo.gdal.Rmdir(path) VSI_RETVAL
osgeo.gdal.RmdirRecursive(path) VSI_RETVAL
osgeo.gdal.SetFileMetadata(path, metadata, domain, options=None) bool
osgeo.gdal.Sync(pszSource, pszTarget, options=None, callback=0, callback_data=None) bool
osgeo.gdal.UnlinkBatch(files) bool