1 from __future__
import print_function
2 from __future__
import absolute_import
8 from .TkAlExceptions
import AllInOneError
13 Dictionary which handles updates of values for already existing keys 15 adapteddict[key] returns a list of all values associated with key 16 This dictionary is used in the class `BetterConfigParser` instead of the 17 default `dict_type` of the `ConfigParser` class. 22 collections.OrderedDict.__init__(self, *args, **kwargs)
24 def __setitem__(self, key, value, dict_setitem=collections.OrderedDict.__setitem__):
26 od.__setitem__(i, y) <==> od[i]=y 27 Updating an existing key appends the new value to the old value 28 instead of replacing it. 31 - `key`: key part of the key-value pair 32 - `value`: value part of the key-value pair 33 - `dict_item`: method which is used for finally setting the item 36 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
37 if isinstance(value, (str, unicode)):
39 if item == (key, value.split(
"\n")):
42 self.validationslist.append((key, value))
44 dict_setitem(self, key, value)
47 if key !=
"__name__" and "__name__" in self
and self[
"__name__"]==
"validation":
48 return [validation[1]
for validation
in self.
validationslist if validation[0] == key]
50 return collections.OrderedDict.__getitem__(self, key)
53 if "__name__" in self
and self[
"__name__"]==
"validation":
56 return collections.OrderedDict.items(self)
60 ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
68 items = self.
items(section)
69 except ConfigParser.NoSectionError:
79 for option
in self.options( section ):
80 result[option] = self.get( section, option )
81 if "local"+section.title()
in self.sections():
82 for option
in self.options(
"local"+section.title() ):
83 result[option] = self.get(
"local"+section.title(),
85 except ConfigParser.NoSectionError
as section:
86 msg = (
"%s in configuration files. This section is mandatory." 92 result = copy.deepcopy(defaultDict)
93 for option
in demandPars:
95 result[option] = self.get( section, option )
96 except ConfigParser.NoOptionError
as globalSectionError:
97 globalSection =
str( globalSectionError ).
split(
"'" )[-2]
98 splittedSectionName = section.split(
":" )
99 if len( splittedSectionName ) > 1:
100 localSection = (
"local"+section.split(
":" )[0].
title()+
":" 101 +section.split(
":")[1])
103 localSection = (
"local"+section.split(
":" )[0].
title())
104 if self.has_section( localSection ):
106 result[option] = self.get( localSection, option )
107 except ConfigParser.NoOptionError
as option:
108 msg = (
"%s. This option is mandatory." 111 "section '"+globalSection+
"' or", 1)))
114 msg = (
"%s. This option is mandatory." 115 %(
str(globalSectionError).
replace(
":",
"", 1)))
119 except AllInOneError:
126 for section
in self.sections():
127 if "alignment:" in section:
128 alignments.append(
Alignment( section.split(
"alignment:" )[1],
130 names_after_cleaning = [alignment.name
for alignment
in alignments]
133 in collections.Counter(names_after_cleaning).
items()
135 if len(duplicates) > 0:
136 msg =
"Duplicate alignment names after removing invalid characters: " 137 msg +=
", ".
join(duplicates) +
"\n" 138 msg +=
"Please rename the alignments to avoid name clashes." 144 for section
in self.sections():
145 if "compare:" in section:
147 knownSimpleOptions = [
"levels",
"dbOutput",
"moduleList",
"modulesToPlot",
"useDefaultRange",
"plotOnlyGlobal",
"plotPng",
"makeProfilePlots",
148 "dx_min",
"dx_max",
"dy_min",
"dy_max",
"dz_min",
"dz_max",
"dr_min",
"dr_max",
"rdphi_min",
"rdphi_max",
149 "dalpha_min",
"dalpha_max",
"dbeta_min",
"dbeta_max",
"dgamma_min",
"dgamma_max",
150 "jobmode",
"3DSubdetector1",
"3Dubdetector2",
"3DTranslationalScaleFactor",
"jobid",
"multiIOV"])
151 levels = self.get( section,
"levels" )
152 dbOutput = self.get( section,
"dbOutput" )
153 compares[section.split(
":")[1]] = ( levels, dbOutput )
158 "jobmode":
"interactive",
159 "datadir":os.getcwd(),
160 "logdir":os.getcwd(),
165 self.
checkInput(
"general", knownSimpleOptions = defaults.keys() + mandatories)
166 general = self.
getResultingSection(
"general", defaultDict = defaults, demandPars = mandatories )
167 internal_section =
"internals" 168 if not self.has_section(internal_section):
169 self.add_section(internal_section)
170 if not self.has_option(internal_section,
"workdir"):
171 self.
set(internal_section,
"workdir",
"/tmp/$USER")
172 if not self.has_option(internal_section,
"scriptsdir"):
173 self.
set(internal_section,
"scriptsdir",
None)
176 general[
"workdir"] = self.get(internal_section,
"workdir")
177 general[
"scriptsdir"] = self.get(internal_section,
"scriptsdir")
178 for folder
in "workdir",
"datadir",
"logdir",
"eosdir":
179 general[folder] = os.path.expandvars(general[folder])
183 def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
186 Method which checks, if the given options in `section` are in the 187 list of `knownSimpleOptions` or match an item of `knownKeywords`. 188 This is basically a check for typos and wrong parameters. 191 - `section`: Section of a configuration file 192 - `knownSimpleOptions`: List of allowed simple options in `section`. 193 - `knownKeywords`: List of allowed keywords in `section`. 197 for option
in self.options( section ):
198 if option
in knownSimpleOptions:
200 elif option.split()[0]
in knownKeywords:
202 elif option
in ignoreOptions:
203 print (
"Ignoring option '%s' in section '[%s]'." 206 msg = (
"Invalid or unknown parameter '%s' in section '%s'!" 209 except ConfigParser.NoSectionError:
212 def set(self, section, option, value=None):
214 ConfigParser.ConfigParser.set(self, section, option, value)
215 except ConfigParser.NoSectionError:
216 self.add_section(section)
217 ConfigParser.ConfigParser.set(self, section, option, value)
219 def items(self, section, raw=False, vars=None):
220 if section ==
"validation":
222 raise NotImplementedError(
"'raw' and 'vars' do not work for betterConfigParser.items()!")
223 items = self._sections[
"validation"].
items()
226 return ConfigParser.ConfigParser.items(self, section, raw, vars)
229 """Write an .ini-format representation of the configuration state.""" 230 for section
in self._sections:
231 fp.write(
"[%s]\n" % section)
232 for (key, value)
in self._sections[section].
items():
233 if key ==
"__name__" or not isinstance(value, (str, unicode)):
235 if value
is not None:
237 fp.write(
"%s\n" % (key))
244 OPTCRE_VALIDATION = re.compile(
246 r'(?P<preexisting>preexisting)?' 248 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)