ecmwf / eccodes-python

Python interface to the ecCodes GRIB/BUFR decoder/encoder
Apache License 2.0
115 stars 33 forks source link

Documentation lacking #39

Closed adybbroe closed 4 years ago

adybbroe commented 4 years ago

Hi, I am completely new to ecCodes. Thought it should be possible doing the equivalent to os.system("grib_copy -w gridType=regular_ll " + nhsp_file + " " + tmp_filename) from Python instead of via a system call.

But can't really find any useful documentation on the Python interfaces. It must be there somewhere!?

shahramn commented 4 years ago

Have a look in https://confluence.ecmwf.int/display/ECC/GRIB+examples Under each child page there are API examples in C, Fortran and Python

adybbroe commented 4 years ago

Thanks for the quick response @shahramn ! The one I thought would have been relevant for me grib_copy_message didn't have a description of the Python API. Anyhow, I continue with my system call. It will take me more time than I have for this now to dig out the necessary procedures required to do the same in Python.

shahramn commented 4 years ago

Perhaps you want something like this:

import traceback
import sys
from eccodes import *

VERBOSE = 1  # verbose error reporting

def example(INPUT, OUTPUT):
    fin = open(INPUT, 'rb')
    fout = open(OUTPUT, 'wb')

    while 1:
        gid = codes_grib_new_from_file(fin)
        if gid is None:
            break
        count = codes_get(gid, 'count')

        gridType = codes_get(gid, 'gridType')
        if gridType == 'regular_ll':
            print('Write out message ', count)
            codes_write(gid, fout)
        else:
            print('Skipping message ', count)

        codes_release(gid)

    fin.close()
    fout.close()

def main():
    try:
        example(sys.argv[1], sys.argv[2])
    except CodesInternalError as err:
        if VERBOSE:
            traceback.print_exc(file=sys.stderr)
        else:
            sys.stderr.write(err.msg + '\n')

        return 1

if __name__ == "__main__":
    sys.exit(main())
adybbroe commented 4 years ago

Thanks, that might be useful