OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
uber_par_file_reader.py
Go to the documentation of this file.
1 
2 """
3 Module providing the ParReader class for reading parameter files for the
4 multilevel_processor.py program.
5 """
6 
7 import os
8 import re
9 import sys
10 
11 __author__ = 'melliott'
12 
13 SECTION_HEADER_TEXT = 'section'
14 VALID_KEYS = ['deletefiles', 'overwrite', 'use_existing', 'use_ancillary', 'odir', 'ifile']
15 
16 # class DuplicateEntry(Exception):
17 # """
18 # Exception class for duplicate entries in a section dictionary.
19 # """
20 # def __init__(self, value):
21 # super(DuplicateEntry, self).__init__()
22 # self.value = value
23 
24 # def __str__(self):
25 # return repr(self.value)
26 
27 # class InvalidEntry(Exception):
28 # """
29 # Exception class for invalid entries in a main section dictionary.
30 # """
31 # def __init__(self, value):
32 # super(InvalidEntry, self).__init__()
33 # self.value = value
34 
35 # def __str__(self):
36 # return repr(self.value)
37 
38 def add_par_entry(the_dict, the_key, val_to_add):
39  """
40  Adds an entry to the par file part of the passed in section dictionary.
41  """
42  if the_key in the_dict:
43  the_dict[the_key].append(val_to_add)
44  else:
45  the_dict[the_key] = [val_to_add]
46 
47 def add_sect_entry(filename, sect_key, the_dict, the_key, val_to_add):
48  """
49  Adds an entry to a section dictionary.
50  """
51  if sect_key != 'main':
52  if the_key not in the_dict:
53  the_dict[the_key] = val_to_add
54  else:
55  err_msg = 'Duplicate entry found for {0} in {1}'.format(the_key, filename)
56  sys.exit(err_msg)
57  else:
58  if is_key_valid(the_key):
59  if the_key not in the_dict:
60  the_dict[the_key] = val_to_add
61  else:
62  err_msg = 'Duplicate entry found for {0} in {1}'.format(the_key, filename)
63  sys.exit(err_msg)
64  else:
65  err_msg = 'Invalid entry {0} found in {1}'.format(the_key, filename)
66  sys.exit(err_msg)
67 
68 
69 def get_sect_key(line):
70  """
71  Returns the section name from a line of text.
72  The line is expected to be of the form '# section SECTION_NAME' (without the quotes).
73  """
74  sect_key = ''
75  sect_key = re.sub(r'^\s*\[\s*(.*?)\s*\]\s*$', '\\1', line)
76 # sect_key = re.sub('\s*\[\s*', '', line)
77 # sect_key = re.sub('\s*\]\s*', '', sect_key)
78  return sect_key
79 
81  """
82  Returns True if a line is the header for a new section; returns False otherwise.
83  """
84  section_pattern = r'\s*\[\s*\S+.*\]\s*'
85  compiled_pattern = re.compile(section_pattern, re.IGNORECASE)
86  if re.search(compiled_pattern, line.strip()):
87  return True
88  else:
89  return False
90 
91 def is_key_valid(key_str):
92  """
93  Returns True if opt is one of the valid options for Main section.
94  """
95  key_valid = False
96  if key_str in VALID_KEYS:
97  key_valid = True
98  return key_valid
99 
101  """
102  Returns True if an entire line is a comment; returns False otherwise.
103  """
104  if line.lstrip()[0:1] == '#':
105  return True
106  else:
107  return False
108 
109 class ParReader(object):
110  """
111  A class to perform reading of a seadas_processor.py parameter file.
112  """
113  def __init__(self, fname, acceptable_single_keys, section_converter=None):
114  """
115  Initializes the ParReader object: Confirms that the passed in file
116  exists, is a regular file, and is readable. If those are all true,
117  sets the object filename value to the passed in value.
118  """
119  if os.path.exists(fname):
120  if os.path.isfile(fname):
121  if os.access(fname, os.R_OK):
122  self.filename = fname
123  self.acceptable_single_keys = acceptable_single_keys
124  self.section_converter = section_converter
125  self.par_results = {}
126  else:
127  err_msg = "Error! Unable to read {0}.".format(fname)
128  sys.exit(err_msg)
129  else:
130  err_msg = "Error! {0} is not a regular file.".format(fname)
131  sys.exit(err_msg)
132  else:
133  err_msg = "Error! File {0} could not be found.".format(fname)
134  sys.exit(err_msg)
135 
136  def _start_new_section(self, hdr_line):
137  """
138  Initializes a new section of the dictionary to be returned.
139  """
140  sect_dict = {}
141  sect_key = get_sect_key(hdr_line)
142  self.par_results[sect_key] = sect_dict
143  if self.section_converter:
144  if not (sect_key in list(self.section_converter.keys())):
145  err_msg = 'Error! Section name "{0}" is not recognized.'.\
146  format(sect_key)
147  sys.exit(err_msg)
148  return sect_dict, sect_key
149 
150  def read_par_file(self):
151  """
152  Parses a parameter file, returning the contents in a dictionary of
153  dictionaries. The "outer" dictionary contains each section. The "inner"
154  dictionaries contain the parameter/value pairs.
155  """
156  sect_key = None
157  sect_dict = {}
158  with open(self.filename, 'rt') as par_file:
159  for line in par_file.readlines():
160  line = line.strip()
161  if line != '' and not is_whole_line_comment(line):
162  if is_section_header(line):
163  sect_dict, sect_key = self._start_new_section(line)
164  else:
165  if sect_key != None:
166  if line.find('=') != -1:
167  key, val = line.split('=', 2)
168  if key == 'par':
169  add_par_entry(sect_dict, 'par',
170  val.strip().strip('"').strip("'"))
171  else:
172 
173  add_sect_entry(self.filename, sect_key, sect_dict, key,
174  val.strip().strip('"').strip("'"))
175  # if sect_key != 'main':
176  # add_sect_entry(sect_dict, key,
177  # val.strip().strip('"').strip("'"))
178  # else:
179  # if is_key_valid(key):
180  # add_sect_entry(sect_dict, key,
181  # val.strip().strip('"').strip("'"))
182  # else:
183  # err_msg = '{0} is not a valid key for main section'.format(key)
184  # sys.exit(err_msg)
185  # except DuplicateEntry as dup_exc:
186  # err_msg = 'Duplicate entry found for {0} in {1}'.format(str(dup_exc), self.filename)
187  # sys.exit(err_msg)
188  # except InvalidEntry as invalid_exc:
189  # err_msg = 'Invalid entry found for {0} in {1}'.format(str(invalid_exc), self.filename)
190  # sys.exit(err_msg)
191  elif line.strip in self.acceptable_single_keys:
192  sect_dict[key] = 'True'
193  else:
194  if line.startswith('--'):
195  add_sect_entry(self.filename, sect_key, sect_dict, line, None)
196  else:
197  err_msg = 'Found entry "{0}" with no value in {1}'.format(line, self.filename)
198  sys.exit(err_msg)
199  else:
200  err_msg = 'Error in {0}, no section header found!'.\
201  format(self.filename)
202  sys.exit(err_msg)
203  if sect_key != '':
204  self.par_results[sect_key] = sect_dict
205  return self.par_results
list(APPEND LIBS ${PGSTK_LIBRARIES}) add_executable(atteph_info_modis atteph_info_modis.c) target_link_libraries(atteph_info_modis $
Definition: CMakeLists.txt:7
def add_sect_entry(filename, sect_key, the_dict, the_key, val_to_add)
def __init__(self, fname, acceptable_single_keys, section_converter=None)
def add_par_entry(the_dict, the_key, val_to_add)