CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
betterConfigParser.py
Go to the documentation of this file.
1 import ConfigParser
2 import os
3 import copy
4 from TkAlExceptions import AllInOneError
5 
6 
8  """
9  Dictionary which handles updates of values for already existing keys
10  in a modified way.
11  Instead of replacing the old value, the new value is appended to the
12  value string separated by `self.getSep()`.
13  This dictionary is used in the class `BetterConfigParser` instead of the
14  default `dict_type` of the `ConfigParser` class.
15  """
16 
17  def getSep(self):
18  """
19  This method returns the separator used to separate the values for
20  duplicate options in a config.
21  """
22  return " |/| "
23 
24  def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
25  """
26  od.__setitem__(i, y) <==> od[i]=y
27  Updating an existing key appends the new value to the old value
28  separated by `self.getSep()` instead of replacing it.
29 
30  Arguments:
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
34  """
35 
36  if "__name__" in self and self["__name__"]=="validation" \
37  and key in self and value!=self[key][0]:
38  the_value = [self[key][0]+self.getSep()+value[0]]
39  else:
40  the_value = value
41  dict_setitem(self, key, the_value)
42 
43 
44 class BetterConfigParser(ConfigParser.ConfigParser):
45  def __init__(self):
46  ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
47  dummyDict = AdaptedDict()
48  self._sep = dummyDict.getSep()
49  del dummyDict
50 
51  def getSep(self):
52  return self._sep
53 
54  def optionxform(self, optionstr):
55  return optionstr
56 
57  def exists( self, section, option):
58  try:
59  items = self.items(section)
60  except ConfigParser.NoSectionError:
61  return False
62  for item in items:
63  if item[0] == option:
64  return True
65  return False
66 
67  def __updateDict( self, dictionary, section ):
68  result = dictionary
69  try:
70  for option in self.options( section ):
71  result[option] = self.get( section, option )
72  if "local"+section.title() in self.sections():
73  for option in self.options( "local"+section.title() ):
74  result[option] = self.get( "local"+section.title(),
75  option )
76  except ConfigParser.NoSectionError, section:
77  msg = ("%s in configuration files. This section is mandatory."
78  %(str(section).replace(":", "", 1)))
79  raise AllInOneError(msg)
80  return result
81 
82  def getResultingSection( self, section, defaultDict = {}, demandPars = [] ):
83  result = copy.deepcopy(defaultDict)
84  for option in demandPars:
85  try:
86  result[option] = self.get( section, option )
87  except ConfigParser.NoOptionError, globalSectionError:
88  globalSection = str( globalSectionError ).split( "'" )[-2]
89  splittedSectionName = section.split( ":" )
90  if len( splittedSectionName ) > 1:
91  localSection = ("local"+section.split( ":" )[0].title()+":"
92  +section.split(":")[1])
93  else:
94  localSection = ("local"+section.split( ":" )[0].title())
95  if self.has_section( localSection ):
96  try:
97  result[option] = self.get( localSection, option )
98  except ConfigParser.NoOptionError, option:
99  msg = ("%s. This option is mandatory."
100  %(str(option).replace(":", "", 1).replace(
101  "section",
102  "section '"+globalSection+"' or", 1)))
103  raise AllInOneError(msg)
104  else:
105  msg = ("%s. This option is mandatory."
106  %(str(globalSectionError).replace(":", "", 1)))
107  raise AllInOneError(msg)
108  result = self.__updateDict( result, section )
109  return result
110 
111  def getAlignments( self ):
112  alignments = []
113  for section in self.sections():
114  if "alignment:" in section:
115  alignments.append( Alignment( section.split( "alignment:" )[1],
116  self ) )
117  return alignments
118 
119  def getCompares( self ):
120  compares = {}
121  for section in self.sections():
122  if "compare:" in section:
123  self.checkInput(section,
124  knownSimpleOptions = ["levels", "dbOutput",
125  "jobmode"])
126  levels = self.get( section, "levels" )
127  dbOutput = self.get( section, "dbOutput" )
128  compares[section.split(":")[1]] = ( levels, dbOutput )
129  return compares
130 
131  def getGeneral( self ):
132  defaults = {
133  "jobmode":"interactive",
134  "datadir":os.getcwd(),
135  "logdir":os.getcwd(),
136  "eosdir": "",
137  "email":"true"
138  }
139  self.checkInput("general", knownSimpleOptions = defaults.keys())
140  general = self.getResultingSection( "general", defaultDict = defaults )
141  internal_section = "internals"
142  if not self.has_section(internal_section):
143  self.add_section(internal_section)
144  if not self.has_option(internal_section, "workdir"):
145  self.set(internal_section, "workdir", "/tmp/$USER")
146  general["workdir"] = self.get(internal_section, "workdir")
147  return general
148 
149  def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
150  ignoreOptions=[]):
151  """
152  Method which checks, if the given options in `section` are in the
153  list of `knownSimpleOptions` or match an item of `knownKeywords`.
154  This is basically a check for typos and wrong parameters.
155 
156  Arguments:
157  - `section`: Section of a configuration file
158  - `knownSimpleOptions`: List of allowed simple options in `section`.
159  - `knownKeywords`: List of allowed keywords in `section`.
160  """
161 
162  for option in self.options( section ):
163  if option in knownSimpleOptions:
164  continue
165  elif option.split()[0] in knownKeywords:
166  continue
167  elif option in ignoreOptions:
168  print ("Ignoring option '%s' in section '[%s]'."
169  %(option, section))
170  else:
171  msg = ("Invalid or unknown parameter '%s' in section '%s'!"
172  %(option, section))
173  raise AllInOneError(msg)
174 
double split
Definition: MVATrainer.cc:139