6 from TkAlExceptions
import AllInOneError
11 Dictionary which handles updates of values for already existing keys 13 adapteddict[key] returns a list of all values associated with key 14 This dictionary is used in the class `BetterConfigParser` instead of the 15 default `dict_type` of the `ConfigParser` class. 20 collections.OrderedDict.__init__(self, *args, **kwargs)
22 def __setitem__(self, key, value, dict_setitem=collections.OrderedDict.__setitem__):
24 od.__setitem__(i, y) <==> od[i]=y 25 Updating an existing key appends the new value to the old value 26 instead of replacing it. 29 - `key`: key part of the key-value pair 30 - `value`: value part of the key-value pair 31 - `dict_item`: method which is used for finally setting the item 34 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
35 if isinstance(value, (str, unicode)):
37 if item == (key, value.split(
"\n")):
40 self.validationslist.append((key, value))
42 dict_setitem(self, key, value)
45 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
46 return [validation[1]
for validation
in self.
validationslist if validation[0] == key]
48 return collections.OrderedDict.__getitem__(self, key)
51 if "__name__" in self
and self[
"__name__"]==
"validation":
54 return collections.OrderedDict.items(self)
58 ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
66 items = self.
items(section)
67 except ConfigParser.NoSectionError:
77 for option
in self.options( section ):
78 result[option] = self.get( section, option )
79 if "local"+section.title()
in self.sections():
80 for option
in self.options(
"local"+section.title() ):
81 result[option] = self.get(
"local"+section.title(),
83 except ConfigParser.NoSectionError
as section:
84 msg = (
"%s in configuration files. This section is mandatory." 90 result = copy.deepcopy(defaultDict)
91 for option
in demandPars:
93 result[option] = self.get( section, option )
94 except ConfigParser.NoOptionError
as globalSectionError:
95 globalSection =
str( globalSectionError ).
split(
"'" )[-2]
96 splittedSectionName = section.split(
":" )
97 if len( splittedSectionName ) > 1:
98 localSection = (
"local"+section.split(
":" )[0].
title()+
":" 99 +section.split(
":")[1])
101 localSection = (
"local"+section.split(
":" )[0].
title())
102 if self.has_section( localSection ):
104 result[option] = self.get( localSection, option )
105 except ConfigParser.NoOptionError
as option:
106 msg = (
"%s. This option is mandatory." 109 "section '"+globalSection+
"' or", 1)))
112 msg = (
"%s. This option is mandatory." 113 %(
str(globalSectionError).
replace(
":",
"", 1)))
117 except AllInOneError:
124 for section
in self.sections():
125 if "alignment:" in section:
126 alignments.append(
Alignment( section.split(
"alignment:" )[1],
132 for section
in self.sections():
133 if "compare:" in section:
135 knownSimpleOptions = [
"levels",
"dbOutput",
"moduleList",
"modulesToPlot",
"useDefaultRange",
"plotOnlyGlobal",
"plotPng",
"makeProfilePlots",
136 "dx_min",
"dx_max",
"dy_min",
"dy_max",
"dz_min",
"dz_max",
"dr_min",
"dr_max",
"rdphi_min",
"rdphi_max",
137 "dalpha_min",
"dalpha_max",
"dbeta_min",
"dbeta_max",
"dgamma_min",
"dgamma_max",
138 "jobmode",
"3DSubdetector1",
"3Dubdetector2",
"3DTranslationalScaleFactor",
"jobid"])
139 levels = self.get( section,
"levels" )
140 dbOutput = self.get( section,
"dbOutput" )
141 compares[section.split(
":")[1]] = ( levels, dbOutput )
146 "jobmode":
"interactive",
147 "datadir":os.getcwd(),
148 "logdir":os.getcwd(),
151 self.
checkInput(
"general", knownSimpleOptions = defaults.keys())
153 internal_section =
"internals" 154 if not self.has_section(internal_section):
155 self.add_section(internal_section)
156 if not self.has_option(internal_section,
"workdir"):
157 self.
set(internal_section,
"workdir",
"/tmp/$USER")
158 if not self.has_option(internal_section,
"scriptsdir"):
159 self.
set(internal_section,
"scriptsdir",
None)
162 general[
"workdir"] = self.get(internal_section,
"workdir")
163 general[
"scriptsdir"] = self.get(internal_section,
"scriptsdir")
164 for folder
in "workdir",
"datadir",
"logdir",
"eosdir":
165 general[folder] = os.path.expandvars(general[folder])
169 def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
172 Method which checks, if the given options in `section` are in the 173 list of `knownSimpleOptions` or match an item of `knownKeywords`. 174 This is basically a check for typos and wrong parameters. 177 - `section`: Section of a configuration file 178 - `knownSimpleOptions`: List of allowed simple options in `section`. 179 - `knownKeywords`: List of allowed keywords in `section`. 183 for option
in self.options( section ):
184 if option
in knownSimpleOptions:
186 elif option.split()[0]
in knownKeywords:
188 elif option
in ignoreOptions:
189 print (
"Ignoring option '%s' in section '[%s]'." 192 msg = (
"Invalid or unknown parameter '%s' in section '%s'!" 195 except ConfigParser.NoSectionError:
198 def set(self, section, option, value=None):
200 ConfigParser.ConfigParser.set(self, section, option, value)
201 except ConfigParser.NoSectionError:
202 self.add_section(section)
203 ConfigParser.ConfigParser.set(self, section, option, value)
205 def items(self, section, raw=False, vars=None):
206 if section ==
"validation":
208 raise NotImplementedError(
"'raw' and 'vars' do not work for betterConfigParser.items()!")
209 items = self._sections[
"validation"].
items()
212 return ConfigParser.ConfigParser.items(self, section, raw, vars)
215 """Write an .ini-format representation of the configuration state.""" 216 for section
in self._sections:
217 fp.write(
"[%s]\n" % section)
218 for (key, value)
in self._sections[section].
items():
219 if key ==
"__name__" or not isinstance(value, (str, unicode)):
221 if value
is not None:
223 fp.write(
"%s\n" % (key))
230 OPTCRE_VALIDATION = re.compile(
232 r'(?P<preexisting>preexisting)?' 234 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)