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" and key in self:
37  the_value = self[key]+self.getSep()+value
38  else:
39  the_value = value
40  dict_setitem(self, key, the_value)
41 
42 
43 class BetterConfigParser(ConfigParser.ConfigParser):
44  def __init__(self):
45  ConfigParser.ConfigParser.__init__(self,dict_type=AdaptedDict)
46  dummyDict = AdaptedDict()
47  self._sep = dummyDict.getSep()
48  del dummyDict
49 
50  def getSep(self):
51  return self._sep
52 
53  def optionxform(self, optionstr):
54  return optionstr
55 
56  def exists( self, section, option):
57  try:
58  items = self.items(section)
59  except ConfigParser.NoSectionError:
60  return False
61  for item in items:
62  if item[0] == option:
63  return True
64  return False
65 
66  def __updateDict( self, dictionary, section ):
67  result = dictionary
68  try:
69  for option in self.options( section ):
70  result[option] = self.get( section, option )
71  if "local"+section.title() in self.sections():
72  for option in self.options( "local"+section.title() ):
73  result[option] = self.get( "local"+section.title(),
74  option )
75  except ConfigParser.NoSectionError, section:
76  msg = ("%s in configuration files. This section is mandatory."
77  %(str(section).replace(":", "", 1)))
78  raise AllInOneError(msg)
79  return result
80 
81  def getResultingSection( self, section, defaultDict = {}, demandPars = [] ):
82  result = copy.deepcopy(defaultDict)
83  for option in demandPars:
84  try:
85  result[option] = self.get( section, option )
86  except ConfigParser.NoOptionError, globalSectionError:
87  globalSection = str( globalSectionError ).split( "'" )[-2]
88  splittedSectionName = section.split( ":" )
89  if len( splittedSectionName ) > 1:
90  localSection = ("local"+section.split( ":" )[0].title()+":"
91  +section.split(":")[1])
92  else:
93  localSection = ("local"+section.split( ":" )[0].title())
94  if self.has_section( localSection ):
95  try:
96  result[option] = self.get( localSection, option )
97  except ConfigParser.NoOptionError, option:
98  msg = ("%s. This option is mandatory."
99  %(str(option).replace(":", "", 1).replace(
100  "section",
101  "section '"+globalSection+"' or", 1)))
102  raise AllInOneError(msg)
103  else:
104  msg = ("%s. This option is mandatory."
105  %(str(globalSectionError).replace(":", "", 1)))
106  raise AllInOneError(msg)
107  result = self.__updateDict( result, section )
108  return result
109 
110  def getAlignments( self ):
111  alignments = []
112  for section in self.sections():
113  if "alignment:" in section:
114  alignments.append( Alignment( section.split( "alignment:" )[1],
115  self ) )
116  return alignments
117 
118  def getCompares( self ):
119  compares = {}
120  for section in self.sections():
121  if "compare:" in section:
122  self.checkInput(section,
123  knownSimpleOptions = ["levels", "dbOutput",
124  "jobmode"])
125  levels = self.get( section, "levels" )
126  dbOutput = self.get( section, "dbOutput" )
127  compares[section.split(":")[1]] = ( levels, dbOutput )
128  return compares
129 
130  def getGeneral( self ):
131  defaults = {
132  "jobmode":"interactive",
133  "datadir":os.getcwd(),
134  "logdir":os.getcwd(),
135  "eosdir": "",
136  "email":"true"
137  }
138  self.checkInput("general", knownSimpleOptions = defaults.keys())
139  general = self.getResultingSection( "general", defaultDict = defaults )
140  internal_section = "internals"
141  if not self.has_section(internal_section):
142  self.add_section(internal_section)
143  if not self.has_option(internal_section, "workdir"):
144  self.set(internal_section, "workdir", "/tmp/$USER")
145  general["workdir"] = self.get(internal_section, "workdir")
146  return general
147 
148  def checkInput(self, section, knownSimpleOptions=[], knownKeywords=[],
149  ignoreOptions=[]):
150  """
151  Method which checks, if the given options in `section` are in the
152  list of `knownSimpleOptions` or match an item of `knownKeywords`.
153  This is basically a check for typos and wrong parameters.
154 
155  Arguments:
156  - `section`: Section of a configuration file
157  - `knownSimpleOptions`: List of allowed simple options in `section`.
158  - `knownKeywords`: List of allowed keywords in `section`.
159  """
160 
161  for option in self.options( section ):
162  if option in knownSimpleOptions:
163  continue
164  elif option.split()[0] in knownKeywords:
165  continue
166  elif option in ignoreOptions:
167  print ("Ignoring option '%s' in section '[%s]'."
168  %(option, section))
169  else:
170  msg = ("Invalid or unknown parameter '%s' in section '%s'!"
171  %(option, section))
172  raise AllInOneError(msg)
173 
def replace
Definition: linker.py:10
double split
Definition: MVATrainer.cc:139