Registry / data / pygrib

pygrib

JSON →
library2.1.8pypypi✓ verified 87d ago

Pygrib is a Python module designed for reading and writing GRIB (General Regularly-distributed Information in Binary form) files, which is the World Meteorological Organization (WMO) standard format for weather data. It provides a high-level interface to the ECMWF ECCODES C library, supporting both GRIB edition 1 and edition 2. The library is currently at version 2.1.8 and sees active development with regular releases.

pip install pygrib
INSTALL
IMPORT
SIG · PYGRIB
P
pygrib
datapythonv2.1.8
Install
8.2s avg
Import
504ms
Disk
253MB
Pass rate
5/ 10
Env Coverage5 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.1.8 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
build_error
glibc
py 3.103.920 runs
installs and imports cleanly · install 8.2s · import 0.504s · 251MB
253MB installed
● package 253MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pygrib
import pygrib

This quickstart demonstrates how to open a GRIB file, read a message, and extract key information such as data values, latitudes, and longitudes. Note that a valid GRIB file is required to run this example effectively. The example includes a placeholder for a GRIB file path and a warning if a dummy file is used.

import pygrib import os # Create a dummy GRIB file for demonstration purposes # In a real scenario, you would have an actual GRIB file. # This example can't create a GRIB file from scratch due to pygrib's limitations, # so we simulate reading one. # For actual usage, replace 'sample.grib2' with your file path. # If you don't have one, consider downloading a small sample GRIB file from a meteorological data source. # Example: A minimalist GRIB file (not functional for this code but demonstrates intent) # For this example, assume 'sample.grib2' exists and contains at least one message. # Placeholder for a real GRIB file path grib_file_path = os.environ.get('GRIB_SAMPLE_PATH', 'sample.grib2') # Create a dummy file if it doesn't exist for the example to run without FileNotFoundError if not os.path.exists(grib_file_path): print(f"Warning: '{grib_file_path}' not found. Cannot run quickstart without a GRIB file.\n" \ "Please set the GRIB_SAMPLE_PATH environment variable or create 'sample.grib2'.") # Optionally create a minimal (non-functional) placeholder to prevent immediate crash with open(grib_file_path, 'wb') as f: f.write(b'GRIB-DUMMY-FILE') # Not a valid GRIB file, but prevents FileNotFoundError try: grbs = pygrib.open(grib_file_path) # Read the first message # .read() returns a list of messages, so we take the first element. grb = grbs.read(1)[0] print(f"GRIB Message 1: {grb}") print(f"Short Name: {grb.shortName}") print(f"Parameter Name: {grb.name}") print(f"Units: {grb.units}") print(f"Valid Date: {grb.validDate}") # Get data values (as a numpy array) data = grb.values print(f"Data shape: {data.shape}") print(f"Data min/max: {data.min()}/{data.max()}") # Get latitudes and longitudes lats, lons = grb.latlons() print(f"Latitudes shape: {lats.shape}, Longitudes shape: {lons.shape}") grbs.close() except Exception as e: print(f"An error occurred: {e}") if 'not a GRIB file' in str(e): print("This often means the GRIB_SAMPLE_PATH points to an invalid or empty file.") if os.path.exists(grib_file_path) and os.path.getsize(grib_file_path) < 100: # heuristic for dummy file print("The quickstart created a dummy file; please provide a real GRIB file for full functionality.")
Debug
Known issues
gotchaInstallation can be complex due to the underlying ECCODES C library dependency. On some systems (especially Windows or when building from source), manual installation of ECCODES and setting environment variables like `ECCODES_DEFINITION_PATH` (e.g., to `$CONDA_PREFIX/Library/share/eccodes/definitions`) might be necessary to avoid errors like 'boot.def cannot be found'. Pip/conda generally attempt to handle this automatically, but issues can arise.
fix
Consult the official pygrib installation documentation or `eccodes` documentation for your specific operating system. Ensure `ECCODES_DEFINITION_PATH` is correctly set if you encounter file not found errors related to definitions.
affects: All versions
gotchaOn Anaconda environments, compatibility issues with newer HDF5 library versions (e.g., 1.10.0) have caused `ImportError` due to linking problems with the `ecmwf_grib` dependency.
fix
When using `conda`, explicitly request an older HDF5 version, for example: `conda install pygrib hdf5=1.8`.
affects: Older versions of pygrib (prior to 2.x), especially on Anaconda.
gotchaPygrib has limited capabilities for writing GRIB files. You can modify the contents (e.g., data values) of an *existing* GRIB message and write it, but you cannot create an entirely new GRIB file from scratch.
fix
If creating GRIB files from scratch is needed, consider alternative libraries or tools that offer full GRIB creation capabilities, or start by modifying a minimal template GRIB file.
affects: All versions
gotchaWhen modifying GRIB2 message values (`grb['values']`), the `orderOfSpatialDifferencing` key might be reset to a default (e.g., 0), which can lead to the output GRIB2 file being considered 'unusable' by other GRIB tools (like `wgrib2`).
fix
Before modifying `grb['values']`, store the original `grb['orderOfSpatialDifferencing']`. After setting new values, explicitly set `grb['orderOfSpatialDifferencing']` back to its original value: `original_order = grb['orderOfSpatialDifferencing']; grb['values'] = new_values; grb['orderOfSpatialDifferencing'] = original_order;`.
affects: All versions when writing GRIB2
breakingCompatibility issues have been reported with newer versions of Cython (e.g., > 0.29 and >= 3.1), which might lead to build failures if Cython is not pinned to a compatible version during installation.
fix
If building from source and encountering Cython errors, try pinning Cython to an older, compatible version (e.g., `pip install 'Cython<3.0'`) or ensure you are using the latest `pygrib` version that includes fixes for newer Cython releases.
affects: Versions prior to `2.1.7` (where a fix for Cython >= 3.1 was likely introduced, based on typical release cycles for such issues).
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pygrib'
The pygrib Python package is not installed in the active Python environment.
fix
Install the package using pip or conda: `pip install pygrib` or `conda install -c conda-forge pygrib`.
fatal error C1083: Cannot open include file: 'grib_api.h': No such file or directory
During compilation, the pygrib installation process cannot locate the necessary header files for the underlying ECCODES C library, which pygrib depends on. This is common on Windows or when ECCODES is not correctly installed or its path is not set.
fix
Ensure the ECCODES C library is installed and its path is discoverable. On Linux/macOS, try `conda install -c conda-forge pygrib` which usually includes eccodes. On Windows, installing via `conda install -c conda-forge pygrib` is highly recommended, or manually install ECCODES and set the `ECCODES_DIR` environment variable before installing pygrib from source.
RuntimeError: Key/value not found
This error occurs when attempting to access a GRIB message key (e.g., using `grb['key_name']` or `grbs.select(key='value')`) that does not exist in the GRIB message or file, or when the key is not directly accessible via standard dictionary-like methods in pygrib.
fix
Verify the exact key names available in your GRIB message using `grb.keys()` and ensure you are using the correct key for selection or access. Some keys, like 'analDate' or 'validDate', might be accessible as attributes (e.g., `grb.analDate`) rather than dictionary items.
error: failed building wheel for pygrib
This indicates a general failure during the build process of the pygrib wheel, often due to missing C compilers (like Microsoft Visual C++ Build Tools on Windows) or other critical development dependencies required to compile the underlying C/Cython code.
fix
On Windows, ensure you have the appropriate Visual C++ Build Tools installed (usually part of Visual Studio). For all platforms, using `conda install -c conda-forge pygrib` is often more robust as it pre-compiles and manages the ECCODES dependency, avoiding direct compilation issues.
Upgrade
Version history
2.1.8latest on PyPI · released Oct 26, 2025
Audit
Dependencies
eccodes (C library)requiredPygrib is a Python interface to the ECCODES C library. It is usually installed automatically by pip/conda, but manual installation and environment variable setup might be needed in some cases (e.g., building from source or specific system configurations).
numpyrequiredRequired for array operations and data handling. Older versions of pygrib's setup.py could fail if numpy was not pre-installed.
pyprojrequiredUsed for projection transformations. It's a key dependency.
cythonoptionalOnly needed at build-time for compilation.
Agent activity
22 hits · last 30 days
node
22
Resources