eccodes/examples/python/bufr_clone.py

76 lines
1.7 KiB
Python
Raw Normal View History

2020-01-28 14:32:34 +00:00
# (C) Copyright 2005- ECMWF.
2015-02-09 15:41:15 +00:00
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
2015-11-12 15:15:50 +00:00
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
2015-02-09 15:41:15 +00:00
#
#
# Python implementation: bufr_clone
#
# Description: how to create a new BUFR message by cloning
# an existing message.
#
from __future__ import absolute_import
2021-09-15 11:28:05 +00:00
2015-02-09 15:41:15 +00:00
import sys
2021-09-15 11:28:05 +00:00
import traceback
2015-02-09 15:41:15 +00:00
from eccodes import *
2021-09-15 19:45:34 +00:00
INPUT = "../../data/bufr/syno_1.bufr"
OUTPUT = "bufr_clone_test_p.clone.bufr"
2015-11-11 18:20:31 +00:00
VERBOSE = 1 # verbose error reporting
2015-03-18 10:36:56 +00:00
def example():
2016-10-18 10:55:14 +00:00
# open BUFR file
2021-09-15 19:45:34 +00:00
fin = open(INPUT, "rb")
2015-02-09 15:41:15 +00:00
2016-10-18 10:55:14 +00:00
# open output BUFR file
2021-09-15 19:45:34 +00:00
fout = open(OUTPUT, "wb")
2015-02-09 15:41:15 +00:00
# get handle for message
2016-10-18 10:55:14 +00:00
bufr = codes_bufr_new_from_file(fin)
2015-02-09 15:41:15 +00:00
# create several clones of this message and alter them
# in different ways
2015-11-11 18:20:31 +00:00
for centre in range(0, 3):
2015-02-09 15:41:15 +00:00
# clone the message
2016-10-18 10:55:14 +00:00
clone_id = codes_clone(bufr)
2015-03-18 10:36:56 +00:00
2015-02-09 15:41:15 +00:00
# this is the place where you may wish to modify the clone
2021-09-15 19:45:34 +00:00
codes_set(clone_id, "bufrHeaderCentre", centre)
2015-03-18 10:36:56 +00:00
2015-02-09 15:41:15 +00:00
# write the cloned message to a file
2015-11-11 18:20:31 +00:00
codes_write(clone_id, fout)
2015-03-18 10:36:56 +00:00
2016-09-13 16:48:52 +00:00
# release the clone's handle
2015-02-09 15:41:15 +00:00
codes_release(clone_id)
2015-03-18 10:36:56 +00:00
2015-02-09 15:41:15 +00:00
# release the source's handle
2016-10-18 10:55:14 +00:00
codes_release(bufr)
2015-03-18 10:36:56 +00:00
2015-02-09 15:41:15 +00:00
fin.close()
fout.close()
2015-11-11 18:20:31 +00:00
2015-02-09 15:41:15 +00:00
def main():
try:
example()
2015-11-12 15:15:50 +00:00
except CodesInternalError as err:
2015-02-09 15:41:15 +00:00
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
2021-09-15 19:45:34 +00:00
sys.stderr.write(err.msg + "\n")
2015-02-09 15:41:15 +00:00
return 1
2015-02-09 15:41:15 +00:00
if __name__ == "__main__":
sys.exit(main())