eccodeslib Python Interface to ecCodes

2.46.2.19 · active · verified Tue Apr 14

eccodeslib provides the official Python interface to ECMWF's ecCodes C library, allowing users to encode and decode WMO FM-92 GRIB (editions 1 and 2), BUFR (editions 3 and 4), and GTS abbreviated header messages. It enables reading and writing meteorological data files, accessing keys and values, and iterating over messages. The current version is 2.46.2.19, with releases closely tied to the underlying ecCodes C library development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open a GRIB file, iterate through its messages, extract common metadata keys like 'shortName' and 'paramId', and properly release resources. It highlights the importance of having a sample GRIB file and handles potential `FileNotFoundError` or `CodesInternalError` if the C library is not correctly set up.

import eccodes as ec
import os

# --- This quickstart requires a sample GRIB file. ---
# You can download sample GRIB files from ECMWF's website or find them in
# ecCodes/eccodes-python test directories, e.g., 'tests/data/regular_latlon_surface.grib2'.
# Replace 'path/to/sample.grib' with the actual path to your GRIB file.
# For example, a small GRIB file could be 'https://github.com/ecmwf/eccodes/blob/develop/tests/data/sample.grib2'.

GRIB_FILE_PATH = os.environ.get('ECCODES_SAMPLE_GRIB_PATH', 'path/to/sample.grib')

try:
    print(f"Attempting to read GRIB file: {GRIB_FILE_PATH}")
    message_count = 0
    with open(GRIB_FILE_PATH, 'rb') as f:
        while True:
            # Get a new GRIB message handle from the file
            handle = ec.codes_handle_new_from_file(f, ec.CODES_PRODUCT_GRIB)
            if handle is None:
                break # End of file

            message_count += 1
            # Access common keys
            short_name = ec.codes_get(handle, 'shortName')
            param_id = ec.codes_get_long(handle, 'paramId')
            date = ec.codes_get_long(handle, 'dataDate')
            time = ec.codes_get_long(handle, 'dataTime')

            print(f"  Message {message_count}: shortName={short_name}, paramId={param_id}, Date={date}, Time={time}")

            # Release the handle to free memory
            ec.codes_release(handle)

    if message_count == 0:
        print("No GRIB messages found in the file.")
    else:
        print(f"Successfully processed {message_count} GRIB messages.")

except FileNotFoundError:
    print(f"Error: GRIB file not found at '{GRIB_FILE_PATH}'. Please ensure the file exists or set ECCODES_SAMPLE_GRIB_PATH.")
except ec.CodesInternalError as e:
    print(f"Error processing GRIB file: {e}. Ensure ecCodes C library is installed and the GRIB file is valid.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →