eccodes/examples/python/metar_get_keys.py

97 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-01-28 14:32:34 +00:00
# (C) Copyright 2005- ECMWF.
2015-04-22 16:58:21 +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-04-22 16:58:21 +00:00
#
# Python implementation: metar_get_keys
#
2015-11-12 15:15:50 +00:00
# Description: how to read values of different type of keys from METAR messages
2015-04-22 16:58:21 +00:00
#
#
import sys
2021-09-15 11:28:05 +00:00
import traceback
2015-04-22 16:58:21 +00:00
from eccodes import *
2021-09-15 19:45:34 +00:00
INPUT = "../../data/metar/metar.txt"
2015-11-11 18:20:31 +00:00
VERBOSE = 1 # verbose error reporting
2021-09-15 19:36:30 +00:00
2018-08-02 12:09:09 +00:00
def print_keys(msg_id):
2021-09-15 19:45:34 +00:00
keys = [
"CCCC",
"latitude",
"longitude",
"dateTime",
"elevation",
"temperature",
"dewPointTemperature",
"qnh",
]
2018-08-02 12:09:09 +00:00
for key in keys:
try:
2019-06-12 14:47:22 +00:00
if codes_is_defined(msg_id, key):
2021-09-15 19:45:34 +00:00
print(" %s: %s" % (key, codes_get(msg_id, key)))
2018-08-02 12:09:09 +00:00
except CodesInternalError as err:
print('Error with key="%s" : %s' % (key, err.msg))
2015-04-22 16:58:21 +00:00
2018-08-02 12:09:09 +00:00
def example1():
2018-04-16 10:40:35 +00:00
# open METAR file
2015-04-22 16:58:21 +00:00
f = open(INPUT)
2015-11-11 18:20:31 +00:00
cnt = 0
2015-04-22 16:58:21 +00:00
# loop for the messages in the file
while 1:
# get handle for message
2018-08-02 12:09:09 +00:00
msg_id = codes_metar_new_from_file(f)
if msg_id is None:
2015-11-11 18:20:31 +00:00
break
2015-04-22 16:58:21 +00:00
print("message: %s" % cnt)
2018-08-02 12:09:09 +00:00
print_keys(msg_id)
2015-11-11 18:20:31 +00:00
cnt += 1
2015-04-22 16:58:21 +00:00
# delete handle
2018-08-02 12:09:09 +00:00
codes_release(msg_id)
2015-04-22 16:58:21 +00:00
# close the file
f.close()
2015-11-11 18:20:31 +00:00
2018-08-02 12:09:09 +00:00
def example2():
# This time read from a string rather than a file.
2021-09-15 19:45:34 +00:00
metar_str = "METAR LQMO 022350Z 09003KT 6000 FEW010 SCT035 BKN060 08/08 Q1003="
2018-08-02 12:09:09 +00:00
# get handle for message
msg_id = codes_new_from_message(metar_str)
print("\nFrom string: '%s'" % metar_str)
print_keys(msg_id)
codes_release(msg_id)
2015-04-22 16:58:21 +00:00
def main():
try:
2018-08-02 12:09:09 +00:00
example1()
example2()
except CodesInternalError as err:
2015-04-22 16:58:21 +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-04-22 16:58:21 +00:00
return 1
2015-04-22 16:58:21 +00:00
if __name__ == "__main__":
sys.exit(main())