1 from __future__
import print_function
7 from TkAlExceptions
import AllInOneError
12 Dictionary which handles updates of values for already existing keys 14 adapteddict[key] returns a list of all values associated with key 15 This dictionary is used in the class `BetterConfigParser` instead of the 16 default `dict_type` of the `ConfigParser` class. 21 collections.OrderedDict.__init__(self, *args, **kwargs)
23 def __setitem__(self, key, value, dict_setitem=collections.OrderedDict.__setitem__):
25 od.__setitem__(i, y) <==> od[i]=y 26 Updating an existing key appends the new value to the old value 27 instead of replacing it. 30 - `key`: key part of the key-value pair 31 - `value`: value part of the key-value pair 32 - `dict_item`: method which is used for finally setting the item 35 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
36 if isinstance(value, (str, unicode)):
38 if item == (key, value.split(
"\n")):
41 self.validationslist.append((key, value))
43 dict_setitem(self, key, value)
46 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
47 return [validation[1]
for validation
in self.
validationslist if validation[0] == key]
49 return collections.OrderedDict.__getitem__(self, key)
52 if "__name__" in self
and self[
"__name__"]==
"validation":
55 return collections.OrderedDict.items(self)
59 ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
67 items = self.
items(section)
68 except ConfigParser.NoSectionError:
78 for option
in self.options( section ):
79 result[option] = self.get( section, option )
80 if "local"+section.title()
in self.sections():
81 for option
in self.options(
"local"+section.title() ):
82 result[option] = self.get(
"local"+section.title(),
84 except ConfigParser.NoSectionError
as section:
85 msg = (
"%s in configuration files. This section is mandatory." 91 result = copy.deepcopy(defaultDict)
92 for option
in demandPars:
94 result[option] = self.get( section, option )
95 except ConfigParser.NoOptionError
as globalSectionError:
96 globalSection =
str( globalSectionError ).
split(
"'" )[-2]
97 splittedSectionName = section.split(
":" )
98 if len( splittedSectionName ) > 1:
99 localSection = (
"local"+section.split(
":" )[0].
title()+
":" 100 +section.split(
":")[1])
102 localSection = (
"local"+section.split(
":" )[0].
title())
103 if self.has_section( localSection ):
105 result[option] = self.get( localSection, option )
106 except ConfigParser.NoOptionError
as option:
107 msg = (
"%s. This option is mandatory." 110 "section '"+globalSection+
"' or", 1)))
113 msg = (
"%s. This option is mandatory." 114 %(
str(globalSectionError).
replace(
":",
"", 1)))
118 except AllInOneError:
125 for section
in self.sections():
126 if "alignment:" in section:
127 alignments.append(
Alignment( section.split(
"alignment:" )[1],
129 names_after_cleaning = [alignment.name
for alignment
in alignments]
132 in collections.Counter(names_after_cleaning).
items()
134 if len(duplicates) > 0:
135 msg =
"Duplicate alignment names after removing invalid characters: " 136 msg +=
", ".
join(duplicates) +
"\n" 137 msg +=
"Please rename the alignments to avoid name clashes." 143 for section
in self.sections():
144 if "compare:" in section:
146 knownSimpleOptions = [
"levels",
"dbOutput",
"moduleList",
"modulesToPlot",
"useDefaultRange",
"plotOnlyGlobal",
"plotPng",
"makeProfilePlots",
147 "dx_min",
"dx_max",
"dy_min",
"dy_max",
"dz_min",
"dz_max",
"dr_min",
"dr_max",
"rdphi_min",
"rdphi_max",
148 "dalpha_min",
"dalpha_max",
"dbeta_min",
"dbeta_max",
"dgamma_min",
"dgamma_max",
149 "jobmode",
"3DSubdetector1",
"3Dubdetector2",
"3DTranslationalScaleFactor",
"jobid"])
150 levels = self.get( section,
"levels" )
151 dbOutput = self.get( section,
"dbOutput" )
152 compares[section.split(
":")[1]] = ( levels, dbOutput )
157 "jobmode":
"interactive",
158 "datadir":os.getcwd(),
159 "logdir":os.getcwd(),
164 self.
checkInput(
"general", knownSimpleOptions = defaults.keys() + mandatories)
166 internal_section =
"internals" 167 if not self.has_section(internal_section):
168 self.add_section(internal_section)
169 if not self.has_option(internal_section,
"workdir"):
170 self.
set(internal_section,
"workdir",
"/tmp/$USER")
171 if not self.has_option(internal_section,
"scriptsdir"):
172 self.
set(internal_section,
"scriptsdir",
None)
175 general[
"workdir"] = self.get(internal_section,
"workdir")
176 general[
"scriptsdir"] = self.get(internal_section,
"scriptsdir")
177 for folder
in "workdir",
"datadir",
"logdir",
"eosdir":
178 general[folder] = os.path.expandvars(general[folder])
182 def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
185 Method which checks, if the given options in `section` are in the 186 list of `knownSimpleOptions` or match an item of `knownKeywords`. 187 This is basically a check for typos and wrong parameters. 190 - `section`: Section of a configuration file 191 - `knownSimpleOptions`: List of allowed simple options in `section`. 192 - `knownKeywords`: List of allowed keywords in `section`. 196 for option
in self.options( section ):
197 if option
in knownSimpleOptions:
199 elif option.split()[0]
in knownKeywords:
201 elif option
in ignoreOptions:
202 print (
"Ignoring option '%s' in section '[%s]'." 205 msg = (
"Invalid or unknown parameter '%s' in section '%s'!" 208 except ConfigParser.NoSectionError:
211 def set(self, section, option, value=None):
213 ConfigParser.ConfigParser.set(self, section, option, value)
214 except ConfigParser.NoSectionError:
215 self.add_section(section)
216 ConfigParser.ConfigParser.set(self, section, option, value)
218 def items(self, section, raw=False, vars=None):
219 if section ==
"validation":
221 raise NotImplementedError(
"'raw' and 'vars' do not work for betterConfigParser.items()!")
222 items = self._sections[
"validation"].
items()
225 return ConfigParser.ConfigParser.items(self, section, raw, vars)
228 """Write an .ini-format representation of the configuration state.""" 229 for section
in self._sections:
230 fp.write(
"[%s]\n" % section)
231 for (key, value)
in self._sections[section].
items():
232 if key ==
"__name__" or not isinstance(value, (str, unicode)):
234 if value
is not None:
236 fp.write(
"%s\n" % (key))
243 OPTCRE_VALIDATION = re.compile(
245 r'(?P<preexisting>preexisting)?' 247 r'\s*(?(preexisting)|'
def getResultingSection(self, section, defaultDict={}, demandPars=[])
def optionxform(self, optionstr)
def __getitem__(self, key)
def replace(string, replacements)
def __updateDict(self, dictionary, section)
def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[], ignoreOptions=[])
def __init__(self, args, kwargs)
def items(self, section, raw=False, vars=None)
def __setitem__(self, key, value, dict_setitem=collections.OrderedDict.__setitem__)
def exists(self, section, option)
static std::string join(char **cmd)
def set(self, section, option, value=None)