Python3: make examples work in both Python2 and Python3

This commit is contained in:
Shahram Najm 2017-08-09 13:52:53 +01:00
parent 185edecb48
commit 4fd7715e33
36 changed files with 206 additions and 159 deletions

View File

@ -14,9 +14,9 @@
#
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
INPUT = '../../data/bufr/syno_multi.bufr'
@ -46,7 +46,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -59,9 +59,9 @@ def example():
# get the value
key = 'airTemperatureAt2M'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# print the values of the attributes of the key. Attributes themselves
# are keys as well. Their name is constructed like:
@ -69,9 +69,9 @@ def example():
for attr in attrs:
key = 'airTemperatureAt2M' + "->" + attr
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# ------------------------------------------------------------------
# The 2m temperature data element in this message has an associated
@ -82,17 +82,17 @@ def example():
# get the value
key = 'airTemperatureAt2M->percentConfidence'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# print the values of the attributes of the key.
for attr in attrs:
key = 'airTemperatureAt2M->percentConfidence' + "->" + attr
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
cnt += 1

View File

@ -15,10 +15,12 @@
# an existing message.
#
from __future__ import absolute_import
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/syno_1.bufr'
OUTPUT = 'bufr_clone_test_p.clone.bufr'

View File

@ -13,6 +13,7 @@
# Description: How to copy all the values in the data section that are present in the same
# position in the data tree and with the same number of values to the output handle
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
@ -67,7 +68,7 @@ def example(input_filename, output_filename):
def main():
if len(sys.argv) < 3:
print >>sys.stderr, 'Usage: ', sys.argv[0], ' bufr_in bufr_out'
print('Usage: ', sys.argv[0], ' bufr_in bufr_out', file=sys.stderr)
sys.exit(1)
input_filename = sys.argv[1]

View File

@ -10,6 +10,7 @@
# Description: how to encode flight dataset into BUFR
from __future__ import print_function
from datetime import datetime
import traceback
import numpy as np
@ -24,10 +25,10 @@ def example(csvfile, input_filename, output_filename):
fbufrin = open(input_filename, 'rb')
fbufrout = open(output_filename, 'wb')
print 'Using ecCodes version: ', codes_get_api_version()
print('Using ecCodes version: ', codes_get_api_version())
# The first line in the CSV has the column names
print 'Reading input CSV file: ', csvfile
print('Reading input CSV file: ', csvfile)
parse_date = lambda x: datetime.strptime(x, '%Y%m%d')
parse_time = lambda x: datetime.strptime(x, '%H:%M:%S')
data = np.genfromtxt(csvfile, delimiter=',', dtype=None, names=True,
@ -51,7 +52,7 @@ def example(csvfile, input_filename, output_filename):
windDirections = data['windDirection']
temperatures = data['temperature']
print 'Reading input BUFR file: ', input_filename
print('Reading input BUFR file: ', input_filename)
bufr = codes_bufr_new_from_file(fbufrin)
codes_set(bufr, 'masterTablesVersionNumber', 24)
@ -84,12 +85,12 @@ def example(csvfile, input_filename, output_filename):
codes_set(bufr, 'pack', 1)
codes_write(bufr, fbufrout)
print 'Created output BUFR file: ', output_filename
print('Created output BUFR file: ', output_filename)
def main():
if len(sys.argv) < 4:
print >>sys.stderr, 'Usage: ', sys.argv[0], ' csv bufr_in bufr_out'
print('Usage: ', sys.argv[0], ' csv bufr_in bufr_out', file=sys.stderr)
sys.exit(1)
csv_filename = sys.argv[1]

View File

@ -14,10 +14,13 @@
#
#
from __future__ import absolute_import
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/syno_1.bufr'
VERBOSE = 1 # verbose error reporting
@ -37,7 +40,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -50,12 +53,12 @@ def example():
# get size
num = codes_get_size(bufr, key)
print ' size of %s is: %s' % (key, num)
print(' size of %s is: %s' % (key, num))
# get values
values = codes_get_array(bufr, key)
for i in xrange(len(values)):
print " %d %.10e" % (i + 1, values[i])
for i in range(len(values)):
print(" %d %.10e" % (i + 1, values[i]))
cnt += 1

View File

@ -14,10 +14,12 @@
#
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/syno_multi.bufr'
VERBOSE = 1 # verbose error reporting
@ -37,7 +39,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -50,30 +52,30 @@ def example():
key = 'blockNumber'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# Native type integer
key = 'stationNumber'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# Native type float
key = 'airTemperatureAt2M'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# Native type string
key = 'typicalDate'
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# --------------------------------
# get values for an array
@ -83,24 +85,24 @@ def example():
# get size
num = codes_get_size(bufr, key)
print ' size of %s is: %s' % (key, num)
print(' size of %s is: %s' % (key, num))
# get values
values = codes_get_array(bufr, key)
for i in xrange(len(values)):
print " %d %06d" % (i + 1, values[i])
for i in range(len(values)):
print(" %d %06d" % (i + 1, values[i]))
# Native type float
key = 'numericValues'
# get size
num = codes_get_size(bufr, key)
print ' size of %s is: %s' % (key, num)
print(' size of %s is: %s' % (key, num))
# get values
values = codes_get_array(bufr, key)
for i in xrange(len(values)):
print " %d %.10e" % (i + 1, values[i])
for i in range(len(values)):
print(" %d %.10e" % (i + 1, values[i]))
cnt += 1

View File

@ -15,6 +15,7 @@
# keys in a BUFR message.
from __future__ import print_function
import traceback
import sys
@ -38,7 +39,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -52,7 +53,7 @@ def example():
# print key name
keyname = codes_bufr_keys_iterator_get_name(iterid)
print " %s" % keyname
print(" %s" % keyname)
# delete the key iterator
codes_bufr_keys_iterator_delete(iterid)

View File

@ -15,6 +15,7 @@
#
#
from __future__ import print_function
import traceback
import sys
@ -50,14 +51,14 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# print the values for the selected keys from the message
for key in keys:
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
cnt += 1

View File

@ -19,11 +19,12 @@
# understand the structure of these messages.
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/asca_139.bufr'
VERBOSE = 1 # verbose error reporting
@ -43,7 +44,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# We need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -60,7 +61,7 @@ def example():
# Get the total number of subsets.
numObs = codes_get(bufr, "numberOfSubsets")
print ' Number of values: %ld' % (numObs)
print(' Number of values: %ld' % (numObs))
# Get latitude (for all the subsets)
lat = codes_get_array(bufr, "latitude")
@ -74,15 +75,15 @@ def example():
# Check that all arrays are same size
if len(lat) != numObs or len(lon) != numObs or len(bscat) != numObs:
print 'inconsistent array dimension'
print('inconsistent array dimension')
return 1
# Print the values
print "pixel lat lon backscatter"
print "-------------------------------"
print("pixel lat lon backscatter")
print("-------------------------------")
for i in xrange(numObs):
print "%3d %.2f %.2f %.2f" % (i + 1, lat[i], lon[i], bscat[i])
for i in range(numObs):
print("%3d %.2f %.2f %.2f" % (i + 1, lat[i], lon[i], bscat[i]))
cnt += 1

View File

@ -18,6 +18,7 @@
# messages than the one used in the example. It is advised to use bufr_dump to
# understand the structure of the messages.
from __future__ import print_function
import traceback
import sys
@ -67,7 +68,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -76,9 +77,9 @@ def example():
# print the values for the selected keys from the message
for key in keys:
try:
print ' %s: %s' % (key, codes_get(bufr, key))
print(' %s: %s' % (key, codes_get(bufr, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
cnt += 1

View File

@ -19,9 +19,11 @@
# messages than the one used in the example. It is advised to use bufr_dump to
# understand the structure of the messages.
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/PraticaTemp.bufr'
VERBOSE = 1 # verbose error reporting
@ -36,7 +38,7 @@ def example():
bufr = codes_bufr_new_from_file(f)
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data section
codes_set(bufr, 'unpack', 1)
@ -53,10 +55,10 @@ def example():
windSpeed = codes_get_array(bufr, "windSpeed")
blockNumber = codes_get(bufr, "blockNumber")
stationNumber = codes_get(bufr, "stationNumber")
print 'station %d%d' % (blockNumber,stationNumber)
print 'timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance'
print('station %d%d' % (blockNumber,stationNumber))
print('timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance')
for i in range(0,len(windSpeed)-1):
print timePeriod[i],pressure[i],geopotentialHeight[i],latitudeDisplacement[i],longitudeDisplacement[i],airTemperature[i],windDirection[i],windSpeed[i],extendedVerticalSoundingSignificance[i]
print(timePeriod[i],pressure[i],geopotentialHeight[i],latitudeDisplacement[i],longitudeDisplacement[i],airTemperature[i],windDirection[i],windSpeed[i],extendedVerticalSoundingSignificance[i])
cnt += 1
# delete handle
codes_release(bufr)

View File

@ -11,11 +11,13 @@
# Description: how to read data of the ECMWF EPS tropical cyclone tracks encoded in BUFR format.
#
from __future__ import print_function
import traceback
import sys
import collections
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/tropical_cyclone.bufr'
VERBOSE = 1 # verbose error reporting
@ -38,7 +40,7 @@ def example():
if bufr is None:
break
print '**************** MESSAGE: ',cnt+1,' *****************'
print('**************** MESSAGE: ',cnt+1,' *****************')
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -51,10 +53,10 @@ def example():
hour = codes_get(bufr, "hour")
minute= codes_get(bufr, "minute")
print 'Date and time: ', day,'.',month,'.',year,' ',hour,':',minute
print('Date and time: ', day,'.',month,'.',year,' ',hour,':',minute)
stormIdentifier = codes_get(bufr,"stormIdentifier")
print 'Storm identifier: ', stormIdentifier
print('Storm identifier: ', stormIdentifier)
# How many different timePeriod in the data structure?
numberOfPeriods=0
@ -76,19 +78,19 @@ def example():
longitudeCentre = codes_get(bufr,'#1#longitude')
if significance!=1:
print 'ERROR: unexpected #1#meteorologicalAttributeSignificance'
print('ERROR: unexpected #1#meteorologicalAttributeSignificance')
return 1
if (latitudeCentre==CODES_MISSING_DOUBLE) and (longitudeCentre==CODES_MISSING_DOUBLE):
print 'Observed storm centre position missing'
print('Observed storm centre position missing')
else:
print 'Observed storm centre: latitude=',latitudeCentre,' longitude=',longitudeCentre
print('Observed storm centre: latitude=',latitudeCentre,' longitude=',longitudeCentre)
# Location of storm in perturbed analysis
significance = codes_get(bufr,'#2#meteorologicalAttributeSignificance')
if significance!=4:
print 'ERROR: unexpected #2#meteorologicalAttributeSignificance'
print('ERROR: unexpected #2#meteorologicalAttributeSignificance')
return 1
latitudeAnalysis = codes_get_array(bufr,'#2#latitude')
@ -99,7 +101,7 @@ def example():
significance=codes_get(bufr,'#3#meteorologicalAttributeSignificance')
if significance!=3:
print 'ERROR: unexpected #3#meteorologicalAttributeSignificance=', significance
print('ERROR: unexpected #3#meteorologicalAttributeSignificance=', significance)
return 1
latitudeMaxWind0=codes_get_array(bufr,'#3#latitude')
@ -145,7 +147,7 @@ def example():
lon = codes_get_array(bufr, "#%d#longitude" % rank1)
press = codes_get_array(bufr, "#%d#pressureReducedToMeanSeaLevel" % (i + 1))
else:
print 'ERROR: unexpected meteorologicalAttributeSignificance=',significance
print('ERROR: unexpected meteorologicalAttributeSignificance=',significance)
# Location of maximum wind
values = codes_get_array(bufr, "#%d#meteorologicalAttributeSignificance" % rank3)
@ -162,7 +164,7 @@ def example():
lonWind = codes_get_array(bufr, "#%d#longitude" % rank3)
wind10m = codes_get_array(bufr, "#%d#windSpeedAt10M" % (i + 1))
else:
print 'ERROR: unexpected meteorologicalAttributeSignificance=',significanceWind
print('ERROR: unexpected meteorologicalAttributeSignificance=',significanceWind)
for k in range(len(memberNumber)):
data[k][i]=[lat[k],lon[k],press[k],latWind[k],lonWind[k],wind10m[k]]
@ -171,13 +173,13 @@ def example():
# ---------------------------------------- Print the values -------------
for m in range(len(memberNumber)):
print "== Member %d" %memberNumber[m]
print "step latitude longitude pressure latitude longitude wind"
print("== Member %d" %memberNumber[m])
print("step latitude longitude pressure latitude longitude wind")
for s in range(len(timePeriod)):
if data[m][s][0]!=CODES_MISSING_DOUBLE and data[m][s][1]!=CODES_MISSING_DOUBLE:
print " {:>3d}{}{:>6.1f}{}{:>6.1f}{}{:>8.1f}{}{:>6.1f}{}{:>6.1f}{}{:>6.1f}".format(\
print(" {:>3d}{}{:>6.1f}{}{:>6.1f}{}{:>8.1f}{}{:>6.1f}{}{:>6.1f}{}{:>6.1f}".format(\
timePeriod[s],' ',data[m][s][0],' ',data[m][s][1],' ',data[m][s][2],' ',
data[m][s][3],' ',data[m][s][4],' ',data[m][s][5])
data[m][s][3],' ',data[m][s][4],' ',data[m][s][5]))
# -----------------------------------------------------------------------
cnt += 1

View File

@ -14,6 +14,7 @@
#
#
from __future__ import print_function
import traceback
import sys
@ -42,7 +43,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -53,16 +54,16 @@ def example():
# set centre
val = 222
print ' set bufrHeaderCentre to: %d' % val
print(' set bufrHeaderCentre to: %d' % val)
key = 'bufrHeaderCentre'
try:
print ' %s: %s' % (key, codes_set(bufr, key, val))
print(' %s: %s' % (key, codes_set(bufr, key, val)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
# check bufrHeaderCentre's value
print ' %s''s new value is: %d' % (key, codes_get(bufr, key))
print(' %s''s new value is: %d' % (key, codes_get(bufr, key)))
# write modified message to output
codes_write(bufr, fout)

View File

@ -14,10 +14,12 @@
#
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/synop_multi_subset.bufr'
VERBOSE = 1 # verbose error reporting
@ -37,7 +39,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values
@ -46,7 +48,7 @@ def example():
# find out the number of subsets
key = 'numberOfSubsets'
numberOfSubsets = codes_get(bufr, 'numberOfSubsets')
print ' %s: %d' % (key, numberOfSubsets)
print(' %s: %d' % (key, numberOfSubsets))
# loop over the subsets
for i in range(1, numberOfSubsets + 1):
@ -54,13 +56,13 @@ def example():
# read and print some data values
key = '/subsetNumber=%d/blockNumber' % i
print key
print(key)
val = codes_get_long(bufr, key)
print ' %s= %d' % (key, val)
print(' %s= %d' % (key, val))
key = '/subsetNumber=%d/stationNumber' % i
val = codes_get_long(bufr, key)
print ' %s: %d' % (key, val)
print(' %s: %d' % (key, val))
cnt += 1

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback
import sys
@ -30,7 +31,7 @@ def example():
if bufr is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# ECC-448: create a new BUFR handle from the message
# of the original
@ -47,7 +48,7 @@ def example():
# print key name
keyname = codes_bufr_keys_iterator_get_name(iterid)
print " %s" % keyname
print(" %s" % keyname)
# delete the key iterator
codes_bufr_keys_iterator_delete(iterid)

View File

@ -14,7 +14,7 @@
# Description: how to process a file containing a mix of messages
# and print the kind of product (e.g. GRIB, BUFR etc)
from __future__ import print_function
import traceback
import sys
from eccodes import *
@ -24,7 +24,7 @@ VERBOSE = 1 # verbose error reporting
def example():
if len(sys.argv) < 2:
print >>sys.stderr, 'Usage: ', sys.argv[0], ' file'
print('Usage: ', sys.argv[0], ' file', file=sys.stderr)
sys.exit(1)
f = open(sys.argv[1])
@ -33,7 +33,7 @@ def example():
if id is None:
break
print 'product: ', codes_get(id, 'kindOfProduct', str)
print('product: ', codes_get(id, 'kindOfProduct', str))
codes_release(id)

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback
import sys
@ -32,9 +33,9 @@ def example():
for key in keys:
try:
print ' %s: %s' % (key, codes_get(gid, key))
print(' %s: %s' % (key, codes_get(gid, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
codes_release(gid)

View File

@ -14,6 +14,7 @@ import sys
import random
from eccodes import *
from six.moves import range
INPUT = '../../data/constant_field.grib1'
OUTPUT = 'out.clone.grib'

View File

@ -9,10 +9,12 @@
# nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/tigge_pf_ecmwf.grib2'
VERBOSE = 1 # verbose error reporting
@ -40,19 +42,19 @@ def example():
for i in range(mcount):
gid = gid_list[i]
print "processing message number", i + 1
print("processing message number", i + 1)
for key in keys:
print '%s=%g' % (key, codes_get(gid, key))
print('%s=%g' % (key, codes_get(gid, key)))
print 'There are %d, average is %g, min is %g, max is %g' % (
print('There are %d, average is %g, min is %g, max is %g' % (
codes_get_size(gid, 'values'),
codes_get(gid, 'average'),
codes_get(gid, 'min'),
codes_get(gid, 'max')
)
))
print '-' * 100
print('-' * 100)
codes_release(gid)

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback
import sys
@ -35,16 +36,16 @@ def example():
for key in keys:
try:
print ' %s: %s' % (key, codes_get(gid, key))
print(' %s: %s' % (key, codes_get(gid, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
print 'There are %d values, average is %f, min is %f, max is %f' % (
print('There are %d values, average is %f, min is %f, max is %f' % (
codes_get_size(gid, 'values'),
codes_get(gid, 'average'),
codes_get(gid, 'min'),
codes_get(gid, 'max')
)
))
codes_release(gid)

View File

@ -14,6 +14,7 @@
# Description: how to get the message offset
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
@ -23,7 +24,7 @@ VERBOSE = 1 # verbose error reporting
def example():
if len(sys.argv) < 2:
print >>sys.stderr, 'Usage: ', sys.argv[0], ' file'
print('Usage: ', sys.argv[0], ' file', file=sys.stderr)
sys.exit(1)
f = open(sys.argv[1])
@ -32,7 +33,7 @@ def example():
if id is None:
break
print codes_get_message_offset(id)
print(codes_get_message_offset(id))
codes_release(id)

View File

@ -12,11 +12,14 @@
# Description: How to create and use an index to access GRIB messages from
# a file
from __future__ import print_function
import traceback
import sys
import os
from eccodes import *
from six.moves import map
from six.moves import range
INPUT = '../../data/index.grib'
VERBOSE = 1 # verbose error reporting
@ -25,7 +28,7 @@ VERBOSE = 1 # verbose error reporting
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
pools = list(map(tuple, args)) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x + [y] for x in result for y in pool]
@ -52,13 +55,13 @@ def example():
index_vals = []
for key in index_keys:
print "%sSize=%d" % (
print("%sSize=%d" % (
key,
codes_index_get_size(iid, key)
)
))
key_vals = codes_index_get(iid, key)
print " ".join(key_vals)
print(" ".join(key_vals))
index_vals.append(key_vals)
@ -70,8 +73,8 @@ def example():
gid = codes_new_from_index(iid)
if gid is None:
break
print " ".join(["%s=%s" % (key, codes_get(gid, key))
for key in index_keys])
print(" ".join(["%s=%s" % (key, codes_get(gid, key))
for key in index_keys]))
codes_release(gid)
codes_index_release(iid)

View File

@ -8,6 +8,7 @@
# virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
@ -41,9 +42,9 @@ def example(INPUT):
sys.stdout.write("- %d - lat=%.6e lon=%.6e value=" % (i, lat, lon))
if value == missingValue:
print "missing"
print("missing")
else:
print "%.6f" % value
print("%.6f" % value)
i += 1

View File

@ -12,6 +12,7 @@
# for missing values
# (rather than compare each value with the missingValue key)
#
from __future__ import print_function
import traceback
import sys
@ -50,9 +51,9 @@ def example(INPUT):
# Consult bitmap to see if the i'th value is missing
if bitmapPresent and bitmap[i] == 0:
print "missing"
print("missing")
else:
print "%.6f" % value
print("%.6f" % value)
i += 1

View File

@ -9,6 +9,7 @@
# nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
@ -39,7 +40,7 @@ def example():
while codes_keys_iterator_next(iterid):
keyname = codes_keys_iterator_get_name(iterid)
keyval = codes_get_string(iterid, keyname)
print "%s = %s" % (keyname, keyval)
print("%s = %s" % (keyname, keyval))
codes_keys_iterator_delete(iterid)
codes_release(gid)

View File

@ -11,6 +11,7 @@
# Description: how to read data of the ECMWF EPS tropical cyclone tracks encoded in BUFR format.
#
from __future__ import print_function
import traceback
import sys
import os
@ -24,17 +25,17 @@ def do_print(namespace, INPUT):
f = open(INPUT)
first_time = True
print '{'
print ' "messages" : ['
print('{')
print(' "messages" : [')
while 1:
gid = codes_grib_new_from_file(f)
if gid is None:
break
if not first_time:
print ' ,{'
print(' ,{')
else:
print ' {'
print(' {')
first_time = False
iterid = codes_keys_iterator_new(gid, namespace)
@ -44,29 +45,29 @@ def do_print(namespace, INPUT):
keyname = codes_keys_iterator_get_name(iterid)
keyval = codes_get_string(iterid,keyname)
if not f1:
print ','
print(',')
else:
print ''
print('')
f1 = False
print " \"%s\" : \"%s\"" % (keyname,keyval),
print(" \"%s\" : \"%s\"" % (keyname,keyval), end=' ')
print ''
print ' }'
print('')
print(' }')
codes_keys_iterator_delete(iterid)
codes_release(gid)
print ' ]'
print '}'
print(' ]')
print('}')
f.close()
def usage():
progname = os.path.basename(sys.argv[0])
print "Usage: ", progname, "[options] grib_file1 grib_file2 ..."
print 'Options:'
print '\t-n namespace'
print '\t\tAll the keys belonging to namespace are printed.'
print '\t-m Mars keys are printed.'
print ''
print("Usage: ", progname, "[options] grib_file1 grib_file2 ...")
print('Options:')
print('\t-n namespace')
print('\t\tAll the keys belonging to namespace are printed.')
print('\t-m Mars keys are printed.')
print('')
def main():
if len(sys.argv) < 2:
@ -91,14 +92,14 @@ def main():
for arg in args:
do_print(namespace, arg)
except getopt.GetoptError as err:
print 'Error: ',err
print('Error: ',err)
usage()
return 1
except GribInternalError as err:
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print >>sys.stderr,err.msg
print(err.msg, file=sys.stderr)
return 1

View File

@ -13,6 +13,7 @@ import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/sample.grib2'
OUTPUT = 'out.mw.grib'

View File

@ -9,10 +9,12 @@
# nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/reduced_gaussian_lsm.grib1'
VERBOSE = 1 # verbose error reporting
@ -26,16 +28,16 @@ def example():
for lat, lon in points:
nearest = codes_grib_find_nearest(gid, lat, lon)[0]
print lat, lon
print nearest.lat, nearest.lon, nearest.value, nearest.distance, \
nearest.index
print(lat, lon)
print(nearest.lat, nearest.lon, nearest.value, nearest.distance, \
nearest.index)
four = codes_grib_find_nearest(gid, lat, lon, is_lsm=False, npoints=4)
for i in range(len(four)):
print "- %d -" % i
print four[i]
print("- %d -" % i)
print(four[i])
print "-" * 100
print("-" * 100)
codes_release(gid)
f.close()

View File

@ -9,10 +9,12 @@
# nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/regular_latlon_surface.grib1'
VERBOSE = 1 # verbose error reporting
@ -23,13 +25,13 @@ def example():
gid = codes_grib_new_from_file(f)
values = codes_get_values(gid)
for i in xrange(len(values)):
print "%d %.10e" % (i + 1, values[i])
for i in range(len(values)):
print("%d %.10e" % (i + 1, values[i]))
print '%d values found in %s' % (len(values), INPUT)
print('%d values found in %s' % (len(values), INPUT))
for key in ('max', 'min', 'average'):
print '%s=%.10e' % (key, codes_get(gid, key))
print('%s=%.10e' % (key, codes_get(gid, key)))
codes_release(gid)
f.close()

View File

@ -13,6 +13,7 @@ import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/tp_ecmwf.grib'
OUTPUT = 'p_out.grib_samples.grib'

View File

@ -6,9 +6,11 @@
# 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.
from __future__ import print_function
import traceback
import sys
from eccodes import *
from six.moves import range
INPUT = '../../data/regular_latlon_surface.grib1'
OUTPUT = 'out.set_bitmap_p.grib'
@ -61,7 +63,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print >> sys.stderr, err.msg
print(err.msg, file=sys.stderr)
return 1

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback
import sys
@ -35,27 +36,27 @@ def example():
assert(centreIntVal[0] == 80)
assert(centreStrVal[0] == 'cnmc')
assert(dateStrVal[0] == today)
print 'get centre as an integer - centre = %d' % centreIntVal[0]
print 'get centre as a string - centre = %s' % centreStrVal[0]
print 'get date as a string - date = %s' % dateStrVal[0]
print('get centre as an integer - centre = %d' % centreIntVal[0])
print('get centre as a string - centre = %s' % centreStrVal[0])
print('get date as a string - date = %s' % dateStrVal[0])
# Now do the same but using set_key_vals, setting keys all at once
print 'set keys using one long comma-separated string...'
print('set keys using one long comma-separated string...')
codes_set_key_vals(gid, 'level=1,centre=98')
assert(codes_get(gid, 'centre', str) == 'ecmf')
assert(codes_get(gid, 'level', int) == 1)
print 'set keys using a list of strings...'
print('set keys using a list of strings...')
codes_set_key_vals(gid, ['level=2', 'centre=kwbc'])
assert(codes_get(gid, 'centre', int) == 7)
assert(codes_get(gid, 'level', int) == 2)
print 'set keys using a dictionary (order not as specified!)...'
print('set keys using a dictionary (order not as specified!)...')
codes_set_key_vals(gid, {'level': 3, 'centre': 84})
assert(codes_get(gid, 'centre', str) == 'lfpw')
assert(codes_get(gid, 'level', int) == 3)
print 'set keys using an ordered dictionary...'
print('set keys using an ordered dictionary...')
codes_set_key_vals(gid, OrderedDict( [('level', 3), ('centre', 84)] ))
assert(codes_get(gid, 'centre', str) == 'lfpw')
assert(codes_get(gid, 'level', int) == 3)

View File

@ -14,6 +14,7 @@
#
#
from __future__ import print_function
import traceback
import sys
@ -37,7 +38,7 @@ def example():
if gid is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# ---------------------------------------------
# get values for keys holding a single value
@ -46,9 +47,9 @@ def example():
for key in keys:
try:
print ' %s: %s' % (key, codes_get(gid, key))
print(' %s: %s' % (key, codes_get(gid, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
cnt += 1

View File

@ -15,6 +15,7 @@ from eccodes import GribIndex
from eccodes import GribMessage
from eccodes.high_level.gribmessage import IndexNotSelectedError
from eccodes import BufrFile, BufrMessage
from six.moves import range
TESTGRIB = "../../data/high_level_api.grib2"
TESTBUFR = "../../data/bufr/syno_multi.bufr"
@ -225,12 +226,12 @@ class TestGribMessage(unittest.TestCase):
"""Metadata is read correctly from GribMessage."""
with GribFile(TESTGRIB) as grib_file:
msg = GribMessage(grib_file)
msg_keys = msg.keys()
msg_keys = list(msg.keys())
for key in KNOWN_GRIB_KEYS:
assert key in msg_keys, "key '%s' not found" % key
# Size of message in bytes
self.assertEqual(msg.size(), 160219)
self.assertEqual(len(msg.keys()), len(msg))
self.assertEqual(len(list(msg.keys())), len(msg))
def test_missing_message_behaviour(self):
"""Key with MISSING value."""
@ -277,7 +278,7 @@ class TestGribMessage(unittest.TestCase):
with GribFile(TESTGRIB) as grib_file:
msg = GribMessage(grib_file)
msg2 = GribMessage(clone=msg)
self.assertSequenceEqual(msg.keys(), msg2.keys())
self.assertSequenceEqual(list(msg.keys()), list(msg2.keys()))
class TestGribIndex(unittest.TestCase):
@ -366,13 +367,13 @@ class TestBufrMessage(unittest.TestCase):
with BufrFile(TESTBUFR) as bufr_file:
msg = BufrMessage(bufr_file)
msg.unpack()
msg_keys = msg.keys()
msg_keys = list(msg.keys())
self.assertEqual(len(msg_keys), 140)
for key in KNOWN_BUFR_KEYS:
assert key in msg_keys
# Size of message in bytes
self.assertEqual(msg.size(), 220)
self.assertEqual(len(msg.keys()), len(msg))
self.assertEqual(len(list(msg.keys())), len(msg))
def test_content(self):
"""Data values are read correctly from BufrMessage."""
@ -404,7 +405,7 @@ class TestBufrMessage(unittest.TestCase):
with BufrFile(TESTBUFR) as bufr_file:
msg = BufrMessage(bufr_file)
msg2 = BufrMessage(clone=msg)
self.assertSequenceEqual(msg.keys(), msg2.keys())
self.assertSequenceEqual(list(msg.keys()), list(msg2.keys()))
def test_copy_data(self):
"""Can copy data section from one message to another"""

View File

@ -9,6 +9,7 @@
# nor does it submit to any jurisdiction.
#
from __future__ import print_function
import traceback
import sys
@ -36,7 +37,7 @@ def example():
while codes_keys_iterator_next(iterid):
keyname = codes_keys_iterator_get_name(iterid)
keyval = codes_get_string(iterid, keyname)
print "%s = %s" % (keyname, keyval)
print("%s = %s" % (keyname, keyval))
codes_keys_iterator_delete(iterid)
codes_release(bid)
@ -51,7 +52,7 @@ def main():
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print >> sys.stderr, err.msg
print(err.msg, file=sys.stderr)
return 1

View File

@ -14,6 +14,7 @@
#
#
from __future__ import print_function
import traceback
import sys
@ -37,7 +38,7 @@ def example():
if gid is None:
break
print "message: %s" % cnt
print("message: %s" % cnt)
# ---------------------------------------------
# get values for keys holding a single value
@ -47,9 +48,9 @@ def example():
for key in keys:
try:
print ' %s: %s' % (key, codes_get(gid, key))
print(' %s: %s' % (key, codes_get(gid, key)))
except CodesInternalError as err:
print 'Error with key="%s" : %s' % (key, err.msg)
print('Error with key="%s" : %s' % (key, err.msg))
cnt += 1