pygdal
pygdal provides virtualenv and setuptools friendly Python bindings for the GDAL (Geospatial Data Abstraction Library) C API. It was created to address installation difficulties with the standard GDAL Python bindings for GDAL versions prior to 3.7. The project maintains a 3.6.* release line as the last for GDAL versions before 3.7, after which GDAL can be installed directly from PyPI. It focuses on offering a more 'pythonic' interface and integrates with NumPy for data handling.
Common errors
-
error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully.
cause This error often indicates issues with the build environment, potentially related to newer `pip` or `setuptools` versions and how they handle project metadata generation.fixTry downgrading `pip` and `setuptools` (e.g., `pip install pip==23.3.2 setuptools==65.5.1`) or ensure you have all necessary build tools and GDAL development headers installed on your system. -
error in pygdal setup command: use_2to3 is invalid.
cause This error appears in older versions of `pygdal` when used with newer `setuptools` versions, as `use_2to3` was a Python 2 to 3 migration tool option that became invalid.fixUpgrade `pygdal` to the latest 3.6.* version. If the problem persists, try downgrading `setuptools` (e.g., `pip install setuptools==58.0.2`). -
ImportError: DLL load failed: The operating system cannot run %1. (or similar DLL/shared library load error on Windows) / ImportError: No module named _gdal (on Linux/macOS)
cause This typically means that the Python bindings cannot find or load the underlying GDAL C library. Common causes include 32-bit Python trying to load 64-bit GDAL (or vice-versa), incorrect `PATH` environment variable, or missing GDAL system installations.fixVerify that your Python architecture (32-bit vs. 64-bit) matches your GDAL installation. Ensure the GDAL C library is correctly installed and its `bin` and `lib` directories are in your system's `PATH` environment variable. For Windows, check `GDAL_DATA` and `GDAL_DRIVER_PATH` environment variables.
Warnings
- breaking pygdal is for GDAL versions older than 3.7. For GDAL 3.7 and later, you should install the official `GDAL` package directly from PyPI. pygdal 3.6.* is the last release of this package.
- gotcha GDAL Python bindings do not raise exceptions by default when errors occur. Instead, they return an error value (like `None`) and print a message to `sys.stdout`.
- gotcha Using a GDAL object (e.g., a raster band) after its parent object (e.g., the dataset it belongs to) has been implicitly or explicitly deleted can lead to crashes. This is particularly noted for GDAL 3.7 and earlier.
- gotcha A version mismatch between the `pygdal` package and the system-installed GDAL C library (e.g., `libgdal-dev` on Linux) is a common cause of installation and runtime issues.
Install
-
pip install pygdal=="$(gdal-config --version).*" -
pip install pygdal -
sudo apt-get install libgdal-dev
Imports
- gdal
import gdal
from osgeo import gdal
- ogr
from osgeo import ogr
- osr
from osgeo import osr
Quickstart
from osgeo import gdal
import os
def open_gdal_dataset(filepath):
"""Opens a GDAL dataset and prints some basic information."""
if not os.path.exists(filepath):
print(f"Error: File not found at {filepath}")
return
# Enable GDAL exceptions for clearer error handling
gdal.UseExceptions()
try:
dataset = gdal.Open(filepath, gdal.GA_ReadOnly)
if dataset is None:
print(f"Could not open {filepath}")
return
print(f"Successfully opened: {filepath}")
print(f"Driver: {dataset.GetDriver().LongName} ({dataset.GetDriver().ShortName})")
print(f"Size: {dataset.RasterXSize}x{dataset.RasterYSize}x{dataset.RasterCount}")
print(f"Projection: {dataset.GetProjection()[:50]}...") # Print first 50 chars
print(f"GeoTransform: {dataset.GetGeoTransform()}")
# Close the dataset implicitly when `dataset` goes out of scope, or explicitly with dataset=None
except Exception as e:
print(f"An error occurred: {e}")
# Example usage (requires a dummy GeoTIFF file, or replace with an existing file path)
# Create a dummy file for demonstration if it doesn't exist
dummy_tif = "dummy.tif"
if not os.path.exists(dummy_tif):
driver = gdal.GetDriverByName("GTiff")
rows, cols = 100, 100
dataset = driver.Create(dummy_tif, cols, rows, 1, gdal.GDT_Byte)
dataset.SetGeoTransform((0, 1, 0, 0, 0, -1))
dataset.SetProjection('GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]')
band = dataset.GetRasterBand(1)
band.WriteArray([[i % 255 for i in range(cols)] for _ in range(rows)])
dataset = None # Close the dataset
open_gdal_dataset(dummy_tif)
# Clean up dummy file
os.remove(dummy_tif)