#!/usr/bin/env python3
# This version does random reads to make a subset.
# The order is determined by code.
#
# This version uses python code to find the match.
# This is slightly faster than using wgrib2 to find the match.
# See cookbook_subset_5.py.
#
# Note: cookbook_subset_6.py is even faster
def find_in_list(string,inv):
# return first string with match
n=0
j=0
for i in range(len(inv)):
if inv[i].find(string) != -1:
n=n+1
j=i
if n == 1:
return inv[j]
if n == 0:
print("No match!")
if n > 1:
print("Multple matches!")
return None
import pywgrib2_s
in_file='a.grb'
out='a_subset_4.grb'
inv_file='@mem:0'
# make inventory file and save it in inv[]
ierr = pywgrib2_s.mk_inv(in_file, inv_file)
print('mk_inv ierr=',ierr)
inv = pywgrib2_s.read_inv(inv_file)
print("read inventory, messages=", len(inv))
# search strings have to start/end with colons
# don't want '50 mb' to match '850 mb'
# or 'TMP' to match 'VTMP'
for field in (':TMP:2 m above ground:', ':PRATE:', ':UGRD:10 m above ground:'):
for date in (20200101000000,20200101060000,20200101120000,20200101180000):
field_date=':D='+str(date)+field
print('processing: ', field_date)
record=find_in_list(field_date, inv)
if record is None:
print("Error did not find ", field_date)
quit()
err=pywgrib2_s.inq(in_file,select=record,grib=out)
print("done out=",out)