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

View File

@ -15,10 +15,12 @@
# an existing message. # an existing message.
# #
from __future__ import absolute_import
import traceback import traceback
import sys import sys
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/syno_1.bufr' INPUT = '../../data/bufr/syno_1.bufr'
OUTPUT = 'bufr_clone_test_p.clone.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 # 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 # position in the data tree and with the same number of values to the output handle
# #
from __future__ import print_function
import traceback import traceback
import sys import sys
from eccodes import * from eccodes import *
@ -67,7 +68,7 @@ def example(input_filename, output_filename):
def main(): def main():
if len(sys.argv) < 3: 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) sys.exit(1)
input_filename = sys.argv[1] input_filename = sys.argv[1]

View File

@ -10,6 +10,7 @@
# Description: how to encode flight dataset into BUFR # Description: how to encode flight dataset into BUFR
from __future__ import print_function
from datetime import datetime from datetime import datetime
import traceback import traceback
import numpy as np import numpy as np
@ -24,10 +25,10 @@ def example(csvfile, input_filename, output_filename):
fbufrin = open(input_filename, 'rb') fbufrin = open(input_filename, 'rb')
fbufrout = open(output_filename, 'wb') 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 # 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_date = lambda x: datetime.strptime(x, '%Y%m%d')
parse_time = lambda x: datetime.strptime(x, '%H:%M:%S') parse_time = lambda x: datetime.strptime(x, '%H:%M:%S')
data = np.genfromtxt(csvfile, delimiter=',', dtype=None, names=True, data = np.genfromtxt(csvfile, delimiter=',', dtype=None, names=True,
@ -51,7 +52,7 @@ def example(csvfile, input_filename, output_filename):
windDirections = data['windDirection'] windDirections = data['windDirection']
temperatures = data['temperature'] temperatures = data['temperature']
print 'Reading input BUFR file: ', input_filename print('Reading input BUFR file: ', input_filename)
bufr = codes_bufr_new_from_file(fbufrin) bufr = codes_bufr_new_from_file(fbufrin)
codes_set(bufr, 'masterTablesVersionNumber', 24) codes_set(bufr, 'masterTablesVersionNumber', 24)
@ -84,12 +85,12 @@ def example(csvfile, input_filename, output_filename):
codes_set(bufr, 'pack', 1) codes_set(bufr, 'pack', 1)
codes_write(bufr, fbufrout) codes_write(bufr, fbufrout)
print 'Created output BUFR file: ', output_filename print('Created output BUFR file: ', output_filename)
def main(): def main():
if len(sys.argv) < 4: 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) sys.exit(1)
csv_filename = sys.argv[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 traceback
import sys import sys
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/syno_1.bufr' INPUT = '../../data/bufr/syno_1.bufr'
VERBOSE = 1 # verbose error reporting VERBOSE = 1 # verbose error reporting
@ -37,7 +40,7 @@ def example():
if bufr is None: if bufr is None:
break break
print "message: %s" % cnt print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors # we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values # i.e. unpack the data values
@ -50,12 +53,12 @@ def example():
# get size # get size
num = codes_get_size(bufr, key) num = codes_get_size(bufr, key)
print ' size of %s is: %s' % (key, num) print(' size of %s is: %s' % (key, num))
# get values # get values
values = codes_get_array(bufr, key) values = codes_get_array(bufr, key)
for i in xrange(len(values)): for i in range(len(values)):
print " %d %.10e" % (i + 1, values[i]) print(" %d %.10e" % (i + 1, values[i]))
cnt += 1 cnt += 1

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -19,9 +19,11 @@
# messages than the one used in the example. It is advised to use bufr_dump to # messages than the one used in the example. It is advised to use bufr_dump to
# understand the structure of the messages. # understand the structure of the messages.
# #
from __future__ import print_function
import traceback import traceback
import sys import sys
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/PraticaTemp.bufr' INPUT = '../../data/bufr/PraticaTemp.bufr'
VERBOSE = 1 # verbose error reporting VERBOSE = 1 # verbose error reporting
@ -36,7 +38,7 @@ def example():
bufr = codes_bufr_new_from_file(f) bufr = codes_bufr_new_from_file(f)
if bufr is None: if bufr is None:
break break
print "message: %s" % cnt print("message: %s" % cnt)
# we need to instruct ecCodes to expand all the descriptors # we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data section # i.e. unpack the data section
codes_set(bufr, 'unpack', 1) codes_set(bufr, 'unpack', 1)
@ -53,10 +55,10 @@ def example():
windSpeed = codes_get_array(bufr, "windSpeed") windSpeed = codes_get_array(bufr, "windSpeed")
blockNumber = codes_get(bufr, "blockNumber") blockNumber = codes_get(bufr, "blockNumber")
stationNumber = codes_get(bufr, "stationNumber") stationNumber = codes_get(bufr, "stationNumber")
print 'station %d%d' % (blockNumber,stationNumber) print('station %d%d' % (blockNumber,stationNumber))
print 'timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance' print('timePeriod pressure geopotentialHeight latitudeDisplacement longitudeDisplacement airTemperature windDirection windSpeed significance')
for i in range(0,len(windSpeed)-1): 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 cnt += 1
# delete handle # delete handle
codes_release(bufr) 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. # Description: how to read data of the ECMWF EPS tropical cyclone tracks encoded in BUFR format.
# #
from __future__ import print_function
import traceback import traceback
import sys import sys
import collections import collections
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/bufr/tropical_cyclone.bufr' INPUT = '../../data/bufr/tropical_cyclone.bufr'
VERBOSE = 1 # verbose error reporting VERBOSE = 1 # verbose error reporting
@ -38,7 +40,7 @@ def example():
if bufr is None: if bufr is None:
break break
print '**************** MESSAGE: ',cnt+1,' *****************' print('**************** MESSAGE: ',cnt+1,' *****************')
# we need to instruct ecCodes to expand all the descriptors # we need to instruct ecCodes to expand all the descriptors
# i.e. unpack the data values # i.e. unpack the data values
@ -51,10 +53,10 @@ def example():
hour = codes_get(bufr, "hour") hour = codes_get(bufr, "hour")
minute= codes_get(bufr, "minute") 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") stormIdentifier = codes_get(bufr,"stormIdentifier")
print 'Storm identifier: ', stormIdentifier print('Storm identifier: ', stormIdentifier)
# How many different timePeriod in the data structure? # How many different timePeriod in the data structure?
numberOfPeriods=0 numberOfPeriods=0
@ -76,19 +78,19 @@ def example():
longitudeCentre = codes_get(bufr,'#1#longitude') longitudeCentre = codes_get(bufr,'#1#longitude')
if significance!=1: if significance!=1:
print 'ERROR: unexpected #1#meteorologicalAttributeSignificance' print('ERROR: unexpected #1#meteorologicalAttributeSignificance')
return 1 return 1
if (latitudeCentre==CODES_MISSING_DOUBLE) and (longitudeCentre==CODES_MISSING_DOUBLE): if (latitudeCentre==CODES_MISSING_DOUBLE) and (longitudeCentre==CODES_MISSING_DOUBLE):
print 'Observed storm centre position missing' print('Observed storm centre position missing')
else: else:
print 'Observed storm centre: latitude=',latitudeCentre,' longitude=',longitudeCentre print('Observed storm centre: latitude=',latitudeCentre,' longitude=',longitudeCentre)
# Location of storm in perturbed analysis # Location of storm in perturbed analysis
significance = codes_get(bufr,'#2#meteorologicalAttributeSignificance') significance = codes_get(bufr,'#2#meteorologicalAttributeSignificance')
if significance!=4: if significance!=4:
print 'ERROR: unexpected #2#meteorologicalAttributeSignificance' print('ERROR: unexpected #2#meteorologicalAttributeSignificance')
return 1 return 1
latitudeAnalysis = codes_get_array(bufr,'#2#latitude') latitudeAnalysis = codes_get_array(bufr,'#2#latitude')
@ -99,7 +101,7 @@ def example():
significance=codes_get(bufr,'#3#meteorologicalAttributeSignificance') significance=codes_get(bufr,'#3#meteorologicalAttributeSignificance')
if significance!=3: if significance!=3:
print 'ERROR: unexpected #3#meteorologicalAttributeSignificance=', significance print('ERROR: unexpected #3#meteorologicalAttributeSignificance=', significance)
return 1 return 1
latitudeMaxWind0=codes_get_array(bufr,'#3#latitude') latitudeMaxWind0=codes_get_array(bufr,'#3#latitude')
@ -145,7 +147,7 @@ def example():
lon = codes_get_array(bufr, "#%d#longitude" % rank1) lon = codes_get_array(bufr, "#%d#longitude" % rank1)
press = codes_get_array(bufr, "#%d#pressureReducedToMeanSeaLevel" % (i + 1)) press = codes_get_array(bufr, "#%d#pressureReducedToMeanSeaLevel" % (i + 1))
else: else:
print 'ERROR: unexpected meteorologicalAttributeSignificance=',significance print('ERROR: unexpected meteorologicalAttributeSignificance=',significance)
# Location of maximum wind # Location of maximum wind
values = codes_get_array(bufr, "#%d#meteorologicalAttributeSignificance" % rank3) values = codes_get_array(bufr, "#%d#meteorologicalAttributeSignificance" % rank3)
@ -162,7 +164,7 @@ def example():
lonWind = codes_get_array(bufr, "#%d#longitude" % rank3) lonWind = codes_get_array(bufr, "#%d#longitude" % rank3)
wind10m = codes_get_array(bufr, "#%d#windSpeedAt10M" % (i + 1)) wind10m = codes_get_array(bufr, "#%d#windSpeedAt10M" % (i + 1))
else: else:
print 'ERROR: unexpected meteorologicalAttributeSignificance=',significanceWind print('ERROR: unexpected meteorologicalAttributeSignificance=',significanceWind)
for k in range(len(memberNumber)): for k in range(len(memberNumber)):
data[k][i]=[lat[k],lon[k],press[k],latWind[k],lonWind[k],wind10m[k]] data[k][i]=[lat[k],lon[k],press[k],latWind[k],lonWind[k],wind10m[k]]
@ -171,13 +173,13 @@ def example():
# ---------------------------------------- Print the values ------------- # ---------------------------------------- Print the values -------------
for m in range(len(memberNumber)): for m in range(len(memberNumber)):
print "== Member %d" %memberNumber[m] print("== Member %d" %memberNumber[m])
print "step latitude longitude pressure latitude longitude wind" print("step latitude longitude pressure latitude longitude wind")
for s in range(len(timePeriod)): for s in range(len(timePeriod)):
if data[m][s][0]!=CODES_MISSING_DOUBLE and data[m][s][1]!=CODES_MISSING_DOUBLE: 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],' ', 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 cnt += 1

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation # granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction. # nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback import traceback
import sys import sys
@ -35,16 +36,16 @@ def example():
for key in keys: for key in keys:
try: try:
print ' %s: %s' % (key, codes_get(gid, key)) print(' %s: %s' % (key, codes_get(gid, key)))
except CodesInternalError as err: 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_size(gid, 'values'),
codes_get(gid, 'average'), codes_get(gid, 'average'),
codes_get(gid, 'min'), codes_get(gid, 'min'),
codes_get(gid, 'max') codes_get(gid, 'max')
) ))
codes_release(gid) codes_release(gid)

View File

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

View File

@ -12,11 +12,14 @@
# Description: How to create and use an index to access GRIB messages from # Description: How to create and use an index to access GRIB messages from
# a file # a file
from __future__ import print_function
import traceback import traceback
import sys import sys
import os import os
from eccodes import * from eccodes import *
from six.moves import map
from six.moves import range
INPUT = '../../data/index.grib' INPUT = '../../data/index.grib'
VERBOSE = 1 # verbose error reporting VERBOSE = 1 # verbose error reporting
@ -25,7 +28,7 @@ VERBOSE = 1 # verbose error reporting
def product(*args, **kwds): def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 # 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 = [[]] result = [[]]
for pool in pools: for pool in pools:
result = [x + [y] for x in result for y in pool] result = [x + [y] for x in result for y in pool]
@ -52,13 +55,13 @@ def example():
index_vals = [] index_vals = []
for key in index_keys: for key in index_keys:
print "%sSize=%d" % ( print("%sSize=%d" % (
key, key,
codes_index_get_size(iid, key) codes_index_get_size(iid, key)
) ))
key_vals = codes_index_get(iid, key) key_vals = codes_index_get(iid, key)
print " ".join(key_vals) print(" ".join(key_vals))
index_vals.append(key_vals) index_vals.append(key_vals)
@ -70,8 +73,8 @@ def example():
gid = codes_new_from_index(iid) gid = codes_new_from_index(iid)
if gid is None: if gid is None:
break break
print " ".join(["%s=%s" % (key, codes_get(gid, key)) print(" ".join(["%s=%s" % (key, codes_get(gid, key))
for key in index_keys]) for key in index_keys]))
codes_release(gid) codes_release(gid)
codes_index_release(iid) 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. # virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
# #
from __future__ import print_function
import traceback import traceback
import sys import sys
@ -41,9 +42,9 @@ def example(INPUT):
sys.stdout.write("- %d - lat=%.6e lon=%.6e value=" % (i, lat, lon)) sys.stdout.write("- %d - lat=%.6e lon=%.6e value=" % (i, lat, lon))
if value == missingValue: if value == missingValue:
print "missing" print("missing")
else: else:
print "%.6f" % value print("%.6f" % value)
i += 1 i += 1

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -13,6 +13,7 @@ import traceback
import sys import sys
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/tp_ecmwf.grib' INPUT = '../../data/tp_ecmwf.grib'
OUTPUT = 'p_out.grib_samples.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 # 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. # virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback import traceback
import sys import sys
from eccodes import * from eccodes import *
from six.moves import range
INPUT = '../../data/regular_latlon_surface.grib1' INPUT = '../../data/regular_latlon_surface.grib1'
OUTPUT = 'out.set_bitmap_p.grib' OUTPUT = 'out.set_bitmap_p.grib'
@ -61,7 +63,7 @@ def main():
if VERBOSE: if VERBOSE:
traceback.print_exc(file=sys.stderr) traceback.print_exc(file=sys.stderr)
else: else:
print >> sys.stderr, err.msg print(err.msg, file=sys.stderr)
return 1 return 1

View File

@ -7,6 +7,7 @@
# granted to it by virtue of its status as an intergovernmental organisation # granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction. # nor does it submit to any jurisdiction.
from __future__ import print_function
import traceback import traceback
import sys import sys
@ -35,27 +36,27 @@ def example():
assert(centreIntVal[0] == 80) assert(centreIntVal[0] == 80)
assert(centreStrVal[0] == 'cnmc') assert(centreStrVal[0] == 'cnmc')
assert(dateStrVal[0] == today) assert(dateStrVal[0] == today)
print 'get centre as an integer - centre = %d' % centreIntVal[0] print('get centre as an integer - centre = %d' % centreIntVal[0])
print 'get centre as a string - centre = %s' % centreStrVal[0] print('get centre as a string - centre = %s' % centreStrVal[0])
print 'get date as a string - date = %s' % dateStrVal[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 # 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') codes_set_key_vals(gid, 'level=1,centre=98')
assert(codes_get(gid, 'centre', str) == 'ecmf') assert(codes_get(gid, 'centre', str) == 'ecmf')
assert(codes_get(gid, 'level', int) == 1) 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']) codes_set_key_vals(gid, ['level=2', 'centre=kwbc'])
assert(codes_get(gid, 'centre', int) == 7) assert(codes_get(gid, 'centre', int) == 7)
assert(codes_get(gid, 'level', int) == 2) 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}) codes_set_key_vals(gid, {'level': 3, 'centre': 84})
assert(codes_get(gid, 'centre', str) == 'lfpw') assert(codes_get(gid, 'centre', str) == 'lfpw')
assert(codes_get(gid, 'level', int) == 3) 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)] )) codes_set_key_vals(gid, OrderedDict( [('level', 3), ('centre', 84)] ))
assert(codes_get(gid, 'centre', str) == 'lfpw') assert(codes_get(gid, 'centre', str) == 'lfpw')
assert(codes_get(gid, 'level', int) == 3) assert(codes_get(gid, 'level', int) == 3)

View File

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

View File

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

View File

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

View File

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