How to use the cfgrib.messages.Message function in cfgrib

To help you get started, we’ve selected a few cfgrib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ecmwf / cfgrib / tests / test_20_messages.py View on Github external
def test_Message_read():
    with open(TEST_DATA) as file:
        res1 = messages.Message.from_file(file)

    assert res1.message_get('paramId') == 129
    assert res1['paramId'] == 129
    assert list(res1)[0] == 'globalDomain'
    assert list(res1.message_grib_keys('time'))[0] == 'dataDate'
    assert 'paramId' in res1
    assert len(res1) > 100

    with pytest.raises(KeyError):
        res1['non-existent-key']

    assert res1.message_get('non-existent-key', default=1) == 1

    res2 = messages.Message.from_message(res1)
    for (k2, v2), (k1, v1) in zip(res2.items(), res1.items()):
        assert k2 == k1
github ecmwf / cfgrib / tests / test_20_messages.py View on Github external
res1['non-existent-key']

    assert res1.message_get('non-existent-key', default=1) == 1

    res2 = messages.Message.from_message(res1)
    for (k2, v2), (k1, v1) in zip(res2.items(), res1.items()):
        assert k2 == k1
        if isinstance(v2, np.ndarray) or isinstance(v1, np.ndarray):
            assert np.allclose(v2, v1)
        else:
            assert v2 == v1

    with open(TEST_DATA) as file:
        with pytest.raises(EOFError):
            while True:
                messages.Message.from_file(file)
github ecmwf / cfgrib / cfgrib / messages.py View on Github external
yield key

    def __setitem__(self, item, value):
        if item in self.computed_keys:
            _, setter = self.computed_keys[item]
            return setter(self, value)
        else:
            return super(ComputedKeysMessage, self).__setitem__(item, value)


@attr.attrs()
class FileStream(collections.abc.Iterable):
    """Iterator-like access to a filestream of Messages."""

    path = attr.attrib(type=str)
    message_class = attr.attrib(default=Message, type=Message, repr=False)
    errors = attr.attrib(
        default='warn', validator=attr.validators.in_(['ignore', 'warn', 'raise'])
    )
    product_kind = attr.attrib(default=eccodes.CODES_PRODUCT_ANY)

    def __iter__(self):
        # type: () -> T.Generator[Message, None, None]
        with open(self.path, 'rb') as file:
            valid_message_found = False
            while True:
                try:
                    yield self.message_from_file(file, errors=self.errors)
                    valid_message_found = True
                except EOFError:
                    if not valid_message_found:
                        raise EOFError("No valid message found in file: %r" % self.path)
github ecmwf / cfgrib / cfgrib / messages.py View on Github external
def __len__(self):
        # type: () -> int
        return sum(1 for _ in self)

    def write(self, file):
        eccodes.codes_write(self.codes_id, file)


@attr.attrs()
class ComputedKeysMessage(Message):
    """Extension of Message class for adding computed keys."""

    computed_keys = attr.attrib(
        default={},
        type=T.Dict[str, T.Tuple[T.Callable[[Message], T.Any], T.Callable[[Message], T.Any]]],
    )

    def __getitem__(self, item):
        if item in self.computed_keys:
            getter, _ = self.computed_keys[item]
            return getter(self)
        else:
            return super(ComputedKeysMessage, self).__getitem__(item)

    def __iter__(self):
        seen = set()
        for key in super(ComputedKeysMessage, self).__iter__():
            yield key
            seen.add(key)
        for key in self.computed_keys:
            if key not in seen:
github ecmwf / cfgrib / cfgrib / messages.py View on Github external
def __iter__(self):
        # type: () -> T.Generator[str, None, None]
        for key in self.message_grib_keys():
            yield key

    def __len__(self):
        # type: () -> int
        return sum(1 for _ in self)

    def write(self, file):
        eccodes.codes_write(self.codes_id, file)


@attr.attrs()
class ComputedKeysMessage(Message):
    """Extension of Message class for adding computed keys."""

    computed_keys = attr.attrib(
        default={},
        type=T.Dict[str, T.Tuple[T.Callable[[Message], T.Any], T.Callable[[Message], T.Any]]],
    )

    def __getitem__(self, item):
        if item in self.computed_keys:
            getter, _ = self.computed_keys[item]
            return getter(self)
        else:
            return super(ComputedKeysMessage, self).__getitem__(item)

    def __iter__(self):
        seen = set()