Gaudi Framework, version v23r7

Home   Generated: Wed Mar 20 2013
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Public Member Functions | Public Attributes | Private Member Functions | Private Attributes | List of all members
EnvConfig.Control.Environment Class Reference

Public Member Functions

def __init__
 
def vars
 
def var
 
def search
 
def declare
 
def append
 
def prepend
 
def set
 
def default
 
def unset
 
def remove
 
def remove_regexp
 
def searchFile
 
def loadXML
 
def startXMLinput
 
def finishXMLinput
 
def writeToFile
 
def writeToXMLFile
 
def presetFromSystem
 
def process
 
def __getitem__
 
def __setitem__
 
def __delitem__
 
def __iter__
 
def __contains__
 
def __len__
 

Public Attributes

 report
 
 separator
 
 searchPath
 
 actions
 
 variables
 
 loadFromSystem
 
 asWriter
 
 writer
 
 loadedFiles
 

Private Member Functions

def _locate
 
def _guessType
 
def _concatenate
 
def _writeVarToXML
 

Private Attributes

 _fileDirStack
 

Detailed Description

object to hold settings of environment

Definition at line 11 of file Control.py.

Constructor & Destructor Documentation

def EnvConfig.Control.Environment.__init__ (   self,
  loadFromSystem = True,
  useAsWriter = False,
  reportLevel = 1,
  searchPath = None 
)
Initial variables to be pushed and setup

append switch between append and prepend for initial variables.
loadFromSystem causes variable`s system value to be loaded on first encounter.
If useAsWriter == True than every change to variables is recorded to XML file.
reportLevel sets the level of messaging.

Definition at line 14 of file Control.py.

14 
15  def __init__(self, loadFromSystem=True, useAsWriter=False, reportLevel=1, searchPath=None):
16  '''Initial variables to be pushed and setup
17 
18  append switch between append and prepend for initial variables.
19  loadFromSystem causes variable`s system value to be loaded on first encounter.
20  If useAsWriter == True than every change to variables is recorded to XML file.
21  reportLevel sets the level of messaging.
22  '''
23  self.report = xmlModule.Report(reportLevel)
24 
25  self.separator = ':'
26 
27  # Prepeare the internal search path for xml files (used by 'include' elements)
28  self.searchPath = ['.']
29  if searchPath is not None:
30  self.searchPath.extend(searchPath)
31  try:
32  self.searchPath.extend(os.environ['ENVXMLPATH'].split(os.pathsep))
33  except KeyError:
34  # ignore if the env variable is not there
35  pass
36 
37  self.actions = {}
38  self.actions['include'] = lambda n, c, h: self.loadXML(self._locate(n, c, h))
39  self.actions['append'] = lambda n, v, _: self.append(n, v)
40  self.actions['prepend'] = lambda n, v, _: self.prepend(n, v)
41  self.actions['set'] = lambda n, v, _: self.set(n, v)
42  self.actions['unset'] = lambda n, v, _: self.unset(n, v)
43  self.actions['default'] = lambda n, v, _: self.default(n, v)
44  self.actions['remove'] = lambda n, v, _: self.remove(n, v)
45  self.actions['remove-regexp'] = lambda n, v, _: self.remove_regexp(n, v)
46  self.actions['declare'] = self.declare
47 
48  self.variables = {}
49 
50  self.loadFromSystem = loadFromSystem
51  self.asWriter = useAsWriter
52  if useAsWriter:
53  self.writer = xmlModule.XMLFile()
54  self.startXMLinput()
55 
56  self.loadedFiles = set()
57 
58  # Prepare the stack for the directory of the loaded file(s)
59  self._fileDirStack = []
60  # Note: cannot use self.declare() because we do not want to write out
61  # the changes to ${.}
62  dot = Variable.Scalar('.', local=True, report=self.report)
63  dot.expandVars = False
64  dot.set('')
65  self.variables['.'] = dot
66 

Member Function Documentation

def EnvConfig.Control.Environment.__contains__ (   self,
  item 
)

Definition at line 353 of file Control.py.

354  def __contains__(self, item):
355  return item in self.variables.keys()
def EnvConfig.Control.Environment.__delitem__ (   self,
  key 
)

Definition at line 346 of file Control.py.

347  def __delitem__(self, key):
348  del self.variables[key]
def EnvConfig.Control.Environment.__getitem__ (   self,
  key 
)

Definition at line 337 of file Control.py.

338  def __getitem__(self, key):
339  return self.variables[key]
def EnvConfig.Control.Environment.__iter__ (   self)

Definition at line 349 of file Control.py.

350  def __iter__(self):
351  for i in self.variables:
352  yield i
def EnvConfig.Control.Environment.__len__ (   self)

Definition at line 356 of file Control.py.

357  def __len__(self):
358  return len(self.variables.keys())
359 
def EnvConfig.Control.Environment.__setitem__ (   self,
  key,
  value 
)

Definition at line 340 of file Control.py.

341  def __setitem__(self, key, value):
342  if key in self.variables.keys():
343  self.report.addWarn('Addition canceled because of duplicate entry. Var: "' + key + '" value: "' + value + '".')
344  else:
345  self.append(key, value)
def EnvConfig.Control.Environment._concatenate (   self,
  value 
)
private
Returns a variable string with separator separator from the values list

Definition at line 321 of file Control.py.

322  def _concatenate(self, value):
323  '''Returns a variable string with separator separator from the values list'''
324  stri = ""
325  for it in value:
326  stri += it + self.separator
327  stri = stri[0:len(stri)-1]
328  return stri
329 
def EnvConfig.Control.Environment._guessType (   self,
  varname 
)
private
Guess the type of the variable from its name: if the name contains
'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.

Definition at line 115 of file Control.py.

116  def _guessType(self, varname):
117  '''
118  Guess the type of the variable from its name: if the name contains
119  'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.
120  '''
121  varname = varname.upper() # make the comparison case insensitive
122  if 'PATH' in varname or 'DIRS' in varname:
123  return 'list'
124  else:
125  return 'scalar'
def EnvConfig.Control.Environment._locate (   self,
  filename,
  caller = None,
  hints = None 
)
private
Find 'filename' in the internal search path.

Definition at line 67 of file Control.py.

67 
68  def _locate(self, filename, caller=None, hints=None):
69  '''
70  Find 'filename' in the internal search path.
71  '''
72  from os.path import isabs, isfile, join, dirname, normpath, abspath
73  if isabs(filename):
74  return filename
75 
76  if hints is None:
77  hints = []
78  elif type(hints) is str:
79  hints = hints.split(self.separator)
80 
81  if caller:
82  calldir = dirname(caller)
83  localfile = join(calldir, filename)
84  if isfile(localfile):
85  return localfile
86  # allow for relative hints
87  hints = [join(calldir, hint) for hint in hints]
88 
89  try:
90  return (abspath(f)
91  for f in [normpath(join(d, filename))
92  for d in self.searchPath + hints]
93  if isfile(f)).next()
94  except StopIteration:
95  from errno import ENOENT
96  raise OSError(ENOENT, 'cannot find file in %r' % self.searchPath, filename)
def EnvConfig.Control.Environment._writeVarToXML (   self,
  name,
  action,
  value,
  vartype = 'list',
  local = 'false' 
)
private
Writes single variable to XML file.

Definition at line 330 of file Control.py.

331  def _writeVarToXML(self, name, action, value, vartype='list', local='false'):
332  '''Writes single variable to XML file.'''
333  if isinstance(value, list):
334  value = self._concatenate(value)
335  self.writer.writeVar(name, action, value, vartype, local)
336 
def EnvConfig.Control.Environment.append (   self,
  name,
  value 
)
Appends to an existing variable.

Definition at line 160 of file Control.py.

161  def append(self, name, value):
162  '''Appends to an existing variable.'''
163  if self.asWriter:
164  self._writeVarToXML(name, 'append', value)
165  else:
166  if name not in self.variables:
167  self.declare(name, self._guessType(name), False)
168  self.variables[name].append(value, self.separator, self.variables)
def EnvConfig.Control.Environment.declare (   self,
  name,
  vartype,
  local 
)
Creates an instance of new variable. It loads values from the OS if the variable is not local.

Definition at line 126 of file Control.py.

127  def declare(self, name, vartype, local):
128  '''Creates an instance of new variable. It loads values from the OS if the variable is not local.'''
129  if self.asWriter:
130  self._writeVarToXML(name, 'declare', '', vartype, local)
131 
132  if not isinstance(local, bool):
133  if str(local).lower() == 'true':
134  local = True
135  else:
136  local = False
137 
138  if name in self.variables.keys():
139  if self.variables[name].local != local:
140  raise Variable.EnvError(name, 'redeclaration')
141  else:
142  if vartype.lower() == "list":
143  if not isinstance(self.variables[name],Variable.List):
144  raise Variable.EnvError(name, 'redeclaration')
145  else:
146  if not isinstance(self.variables[name],Variable.Scalar):
147  raise Variable.EnvError(name, 'redeclaration')
148 
149  if vartype.lower() == "list":
150  a = Variable.List(name, local, report=self.report)
151  else:
152  a = Variable.Scalar(name, local, report=self.report)
153 
154  if self.loadFromSystem and not local and name in os.environ:
155  a.expandVars = False # disable var expansion when importing from the environment
156  a.set(os.environ[name], os.pathsep, environment=self.variables)
157  a.expandVars = True
158 
159  self.variables[name] = a
def EnvConfig.Control.Environment.default (   self,
  name,
  value 
)
Sets a single variable only if it is not already set!

Definition at line 188 of file Control.py.

189  def default(self, name, value):
190  '''Sets a single variable only if it is not already set!'''
191  name = str(name)
192  if self.asWriter:
193  self._writeVarToXML(name, 'default', value)
194  else:
195  # Here it is different from the other actions because after a 'declare'
196  # we cannot tell if the variable was already set or not.
197  # FIXME: improve declare() to allow for a default.
198  if name not in self.variables:
199  if self._guessType(name) == 'list':
200  v = Variable.List(name, False, report=self.report)
201  else:
202  v = Variable.Scalar(name, False, report=self.report)
203  if self.loadFromSystem and name in os.environ:
204  v.set(os.environ[name], os.pathsep, environment=self.variables)
205  else:
206  v.set(value, self.separator, environment=self.variables)
207  self.variables[name] = v
208  else:
209  v = self.variables[name]
210  if not v.val:
211  v.set(value, self.separator, environment=self.variables)
def EnvConfig.Control.Environment.finishXMLinput (   self,
  outputFile = '' 
)
Finishes input of XML file and closes the file.

Definition at line 267 of file Control.py.

268  def finishXMLinput(self, outputFile = ''):
269  '''Finishes input of XML file and closes the file.'''
270  self.writer.writeToFile(outputFile)
271 
def EnvConfig.Control.Environment.loadXML (   self,
  fileName = None,
  namespace = 'EnvSchema' 
)
Loads XML file for input variables.

Definition at line 239 of file Control.py.

240  def loadXML(self, fileName=None, namespace='EnvSchema'):
241  '''Loads XML file for input variables.'''
242  XMLfile = xmlModule.XMLFile()
243  fileName = self._locate(fileName)
244  if fileName in self.loadedFiles:
245  return # ignore recursion
246  self.loadedFiles.add(fileName)
247  dot = self.variables['.']
248  # push the previous value of ${.} onto the stack...
249  self._fileDirStack.append(dot.value())
250  # ... and update the variable
251  dot.set(os.path.dirname(fileName))
252  variables = XMLfile.variable(fileName, namespace=namespace)
253  for i, (action, args) in enumerate(variables):
254  if action not in self.actions:
255  self.report.addError('Node {0}: No action taken with var "{1}". Probably wrong action argument: "{2}".'.format(i, args[0], action))
256  else:
257  self.actions[action](*args) # pylint: disable=W0142
258  # restore the old value of ${.}
259  dot.set(self._fileDirStack.pop())
260  # ensure that a change of ${.} in the file is reverted when exiting it
261  self.variables['.'] = dot
def EnvConfig.Control.Environment.prepend (   self,
  name,
  value 
)
Prepends to an existing variable, or create a new one.

Definition at line 169 of file Control.py.

170  def prepend(self, name, value):
171  '''Prepends to an existing variable, or create a new one.'''
172  if self.asWriter:
173  self._writeVarToXML(name, 'prepend', value)
174  else:
175  if name not in self.variables:
176  self.declare(name, self._guessType(name), False)
177  self.variables[name].prepend(value, self.separator, self.variables)
def EnvConfig.Control.Environment.presetFromSystem (   self)
Loads all variables from the current system settings.

Definition at line 308 of file Control.py.

309  def presetFromSystem(self):
310  '''Loads all variables from the current system settings.'''
311  for k, v in os.environ.items():
312  if k not in self.variables:
313  self.set(k, v)
def EnvConfig.Control.Environment.process (   self)
Call the variable processors on all the variables.

Definition at line 314 of file Control.py.

315  def process(self):
316  '''
317  Call the variable processors on all the variables.
318  '''
319  for v in self.variables.values():
320  v.val = v.process(v.val, self.variables)
def EnvConfig.Control.Environment.remove (   self,
  name,
  value,
  regexp = False 
)
Remove value from variable.

Definition at line 220 of file Control.py.

221  def remove(self, name, value, regexp=False):
222  '''Remove value from variable.'''
223  if self.asWriter:
224  self._writeVarToXML(name, 'remove', value)
225  else:
226  if name not in self.variables:
227  self.declare(name, self._guessType(name), False)
228  self.variables[name].remove(value, self.separator, regexp)
def EnvConfig.Control.Environment.remove_regexp (   self,
  name,
  value 
)

Definition at line 229 of file Control.py.

230  def remove_regexp(self, name, value):
231  self.remove(name, value, True)
232 
def EnvConfig.Control.Environment.search (   self,
  varName,
  expr,
  regExp = False 
)
Searches in a variable for a value.

Definition at line 111 of file Control.py.

112  def search(self, varName, expr, regExp=False):
113  '''Searches in a variable for a value.'''
114  return self.variables[varName].search(expr, regExp)
def EnvConfig.Control.Environment.searchFile (   self,
  filename,
  varName 
)
Searches for appearance of variable in a file.

Definition at line 233 of file Control.py.

234  def searchFile(self, filename, varName):
235  '''Searches for appearance of variable in a file.'''
236  XMLFile = xmlModule.XMLFile()
237  variable = XMLFile.variable(filename, name=varName)
238  return variable
def EnvConfig.Control.Environment.set (   self,
  name,
  value 
)
Sets a single variable - overrides any previous value!

Definition at line 178 of file Control.py.

179  def set(self, name, value):
180  '''Sets a single variable - overrides any previous value!'''
181  name = str(name)
182  if self.asWriter:
183  self._writeVarToXML(name, 'set', value)
184  else:
185  if name not in self.variables:
186  self.declare(name, self._guessType(name), False)
187  self.variables[name].set(value, self.separator, self.variables)
def EnvConfig.Control.Environment.startXMLinput (   self)
Renew writer for new input.

Definition at line 262 of file Control.py.

263  def startXMLinput(self):
264  '''Renew writer for new input.'''
265  self.writer.resetWriter()
266 
def EnvConfig.Control.Environment.unset (   self,
  name,
  value = None 
)
Unsets a single variable to an empty value - overrides any previous value!

Definition at line 212 of file Control.py.

213  def unset(self, name, value=None):# pylint: disable=W0613
214  '''Unsets a single variable to an empty value - overrides any previous value!'''
215  if self.asWriter:
216  self._writeVarToXML(name, 'unset', '')
217  else:
218  if name in self.variables:
219  del self.variables[name]
def EnvConfig.Control.Environment.var (   self,
  name 
)
Gets a single variable. If not available then tries to load from system.

Definition at line 104 of file Control.py.

105  def var(self, name):
106  '''Gets a single variable. If not available then tries to load from system.'''
107  if name in self.variables:
108  return self.variables[name]
109  else:
110  return os.environ[name]
def EnvConfig.Control.Environment.vars (   self,
  strings = True 
)
returns dictionary of all variables optionally converted to string

Definition at line 97 of file Control.py.

97 
98  def vars(self, strings=True):
99  '''returns dictionary of all variables optionally converted to string'''
100  if strings:
101  return dict([(n, v.value(True)) for n, v in self.variables.items()])
102  else:
103  return self.variables
def EnvConfig.Control.Environment.writeToFile (   self,
  fileName,
  shell = 'sh' 
)
Creates an output file with a specified name to be used for setting variables by sourcing this file

Definition at line 272 of file Control.py.

273  def writeToFile(self, fileName, shell='sh'):
274  '''Creates an output file with a specified name to be used for setting variables by sourcing this file'''
275  f = open(fileName, 'w')
276  if shell == 'sh':
277  f.write('#!/bin/bash\n')
278  for variable in self.variables:
279  if not self[variable].local:
280  f.write('export ' +variable+'='+self[variable].value(True, os.pathsep)+'\n')
281  elif shell == 'csh':
282  f.write('#!/bin/csh\n')
283  for variable in self.variables:
284  if not self[variable].local:
285  f.write('setenv ' +variable+' '+self[variable].value(True, os.pathsep)+'\n')
286  else:
287  f.write('')
288  f.write('REM This is an enviroment settings file generated on '+strftime("%a, %d %b %Y %H:%M:%S\n", gmtime()))
289  for variable in self.variables:
290  if not self[variable].local:
291  f.write('set '+variable+'='+self[variable].value(True, os.pathsep)+'\n')
292 
293  f.close()
294 
def EnvConfig.Control.Environment.writeToXMLFile (   self,
  fileName 
)
Writes the current state of environment to a XML file.

NOTE: There is no trace of actions taken, variables are written with a set action only.

Definition at line 295 of file Control.py.

296  def writeToXMLFile(self, fileName):
297  '''Writes the current state of environment to a XML file.
298 
299  NOTE: There is no trace of actions taken, variables are written with a set action only.
300  '''
301  writer = xmlModule.XMLFile()
302  for varName in self.variables:
303  if varName == '.':
304  continue # this is an internal transient variable
305  writer.writeVar(varName, 'set', self.variables[varName].value(True, self.separator))
306  writer.writeToFile(fileName)
307 

Member Data Documentation

EnvConfig.Control.Environment._fileDirStack
private

Definition at line 58 of file Control.py.

EnvConfig.Control.Environment.actions

Definition at line 36 of file Control.py.

EnvConfig.Control.Environment.asWriter

Definition at line 50 of file Control.py.

EnvConfig.Control.Environment.loadedFiles

Definition at line 55 of file Control.py.

EnvConfig.Control.Environment.loadFromSystem

Definition at line 49 of file Control.py.

EnvConfig.Control.Environment.report

Definition at line 22 of file Control.py.

EnvConfig.Control.Environment.searchPath

Definition at line 27 of file Control.py.

EnvConfig.Control.Environment.separator

Definition at line 24 of file Control.py.

EnvConfig.Control.Environment.variables

Definition at line 47 of file Control.py.

EnvConfig.Control.Environment.writer

Definition at line 52 of file Control.py.


The documentation for this class was generated from the following file:
Generated at Wed Mar 20 2013 17:59:48 for Gaudi Framework, version v23r7 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004