Gaudi Framework, version v25r2

Home   Generated: Wed Jun 4 2014
 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
Inheritance diagram for EnvConfig.Control.Environment:
Inheritance graph
[legend]
Collaboration diagram for EnvConfig.Control.Environment:
Collaboration graph
[legend]

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

 log
 
 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 13 of file Control.py.

Constructor & Destructor Documentation

def EnvConfig.Control.Environment.__init__ (   self,
  loadFromSystem = True,
  useAsWriter = False,
  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 16 of file Control.py.

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

Member Function Documentation

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

Definition at line 366 of file Control.py.

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

Definition at line 359 of file Control.py.

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

Definition at line 350 of file Control.py.

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

Definition at line 362 of file Control.py.

363  def __iter__(self):
364  for i in self.variables:
365  yield i
def EnvConfig.Control.Environment.__len__ (   self)

Definition at line 369 of file Control.py.

370  def __len__(self):
371  return len(self.variables.keys())
372 
def EnvConfig.Control.Environment.__setitem__ (   self,
  key,
  value 
)

Definition at line 353 of file Control.py.

354  def __setitem__(self, key, value):
355  if key in self.variables.keys():
356  self.log.warning('Addition canceled because of duplicate entry. Var: "%s" value: "%s".', key, value)
357  else:
358  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 334 of file Control.py.

335  def _concatenate(self, value):
336  '''Returns a variable string with separator separator from the values list'''
337  stri = ""
338  for it in value:
339  stri += it + self.separator
340  stri = stri[0:len(stri)-1]
341  return stri
342 
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 128 of file Control.py.

129  def _guessType(self, varname):
130  '''
131  Guess the type of the variable from its name: if the name contains
132  'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.
133  '''
134  varname = varname.upper() # make the comparison case insensitive
135  if 'PATH' in varname or 'DIRS' in varname:
136  return 'list'
137  else:
138  return 'scalar'
def EnvConfig.Control.Environment._locate (   self,
  filename,
  caller = None,
  hints = None 
)
private
Find 'filename' in the internal search path.

Definition at line 66 of file Control.py.

66 
67  def _locate(self, filename, caller=None, hints=None):
68  '''
69  Find 'filename' in the internal search path.
70  '''
71  from os.path import isabs, isfile, join, dirname, normpath, abspath
72  if isabs(filename):
73  return filename
74 
75  self.log.debug('looking for %s', filename)
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  self.log.debug('trying %s', localfile)
85  if isfile(localfile):
86  self.log.debug('OK (local file)')
87  return localfile
88  # allow for relative hints
89  hints = [join(calldir, hint) for hint in hints]
90 
91  sp = EnvConfig.path + self.searchPath + hints
92  def candidates():
93  for d in sp:
94  f = normpath(join(d, filename))
95  self.log.debug('trying %s', f)
96  yield f
97  try:
98  f = (abspath(f) for f in candidates() if isfile(f)).next()
99  self.log.debug('OK')
100  return f
101  except StopIteration:
102  from errno import ENOENT
103  raise OSError(ENOENT, 'cannot find file in %r' % sp, filename)
def EnvConfig.Control.Environment._writeVarToXML (   self,
  name,
  action,
  value,
  vartype = 'list',
  local = 'false' 
)
private
Writes single variable to XML file.

Definition at line 343 of file Control.py.

344  def _writeVarToXML(self, name, action, value, vartype='list', local='false'):
345  '''Writes single variable to XML file.'''
346  if isinstance(value, list):
347  value = self._concatenate(value)
348  self.writer.writeVar(name, action, value, vartype, local)
349 
def EnvConfig.Control.Environment.append (   self,
  name,
  value 
)
Appends to an existing variable.

Definition at line 173 of file Control.py.

174  def append(self, name, value):
175  '''Appends to an existing variable.'''
176  if self.asWriter:
177  self._writeVarToXML(name, 'append', value)
178  else:
179  if name not in self.variables:
180  self.declare(name, self._guessType(name), False)
181  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 139 of file Control.py.

140  def declare(self, name, vartype, local):
141  '''Creates an instance of new variable. It loads values from the OS if the variable is not local.'''
142  if self.asWriter:
143  self._writeVarToXML(name, 'declare', '', vartype, local)
144 
145  if not isinstance(local, bool):
146  if str(local).lower() == 'true':
147  local = True
148  else:
149  local = False
150 
151  if name in self.variables.keys():
152  if self.variables[name].local != local:
153  raise Variable.EnvError(name, 'redeclaration')
154  else:
155  if vartype.lower() == "list":
156  if not isinstance(self.variables[name],Variable.List):
157  raise Variable.EnvError(name, 'redeclaration')
158  else:
159  if not isinstance(self.variables[name],Variable.Scalar):
160  raise Variable.EnvError(name, 'redeclaration')
161 
162  if vartype.lower() == "list":
163  a = Variable.List(name, local)
164  else:
165  a = Variable.Scalar(name, local)
166 
167  if self.loadFromSystem and not local and name in os.environ:
168  a.expandVars = False # disable var expansion when importing from the environment
169  a.set(os.environ[name], os.pathsep, environment=self.variables)
170  a.expandVars = True
171 
172  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 201 of file Control.py.

202  def default(self, name, value):
203  '''Sets a single variable only if it is not already set!'''
204  name = str(name)
205  if self.asWriter:
206  self._writeVarToXML(name, 'default', value)
207  else:
208  # Here it is different from the other actions because after a 'declare'
209  # we cannot tell if the variable was already set or not.
210  # FIXME: improve declare() to allow for a default.
211  if name not in self.variables:
212  if self._guessType(name) == 'list':
213  v = Variable.List(name, False)
214  else:
215  v = Variable.Scalar(name, False)
216  if self.loadFromSystem and name in os.environ:
217  v.set(os.environ[name], os.pathsep, environment=self.variables)
218  else:
219  v.set(value, self.separator, environment=self.variables)
220  self.variables[name] = v
221  else:
222  v = self.variables[name]
223  if not v.val:
224  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 280 of file Control.py.

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

Definition at line 252 of file Control.py.

253  def loadXML(self, fileName=None, namespace='EnvSchema'):
254  '''Loads XML file for input variables.'''
255  XMLfile = xmlModule.XMLFile()
256  fileName = self._locate(fileName)
257  if fileName in self.loadedFiles:
258  return # ignore recursion
259  self.loadedFiles.add(fileName)
260  dot = self.variables['.']
261  # push the previous value of ${.} onto the stack...
262  self._fileDirStack.append(dot.value())
263  # ... and update the variable
264  dot.set(os.path.dirname(fileName))
265  variables = XMLfile.variable(fileName, namespace=namespace)
266  for i, (action, args) in enumerate(variables):
267  if action not in self.actions:
268  self.log.error('Node {0}: No action taken with var "{1}". Probably wrong action argument: "{2}".'.format(i, args[0], action))
269  else:
270  self.actions[action](*args) # pylint: disable=W0142
271  # restore the old value of ${.}
272  dot.set(self._fileDirStack.pop())
273  # ensure that a change of ${.} in the file is reverted when exiting it
274  self.variables['.'] = dot
def EnvConfig.Control.Environment.prepend (   self,
  name,
  value 
)
Prepends to an existing variable, or create a new one.

Definition at line 182 of file Control.py.

183  def prepend(self, name, value):
184  '''Prepends to an existing variable, or create a new one.'''
185  if self.asWriter:
186  self._writeVarToXML(name, 'prepend', value)
187  else:
188  if name not in self.variables:
189  self.declare(name, self._guessType(name), False)
190  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 321 of file Control.py.

322  def presetFromSystem(self):
323  '''Loads all variables from the current system settings.'''
324  for k, v in os.environ.items():
325  if k not in self.variables:
326  self.set(k, v)
def EnvConfig.Control.Environment.process (   self)
Call the variable processors on all the variables.

Definition at line 327 of file Control.py.

328  def process(self):
329  '''
330  Call the variable processors on all the variables.
331  '''
332  for v in self.variables.values():
333  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 233 of file Control.py.

234  def remove(self, name, value, regexp=False):
235  '''Remove value from variable.'''
236  if self.asWriter:
237  self._writeVarToXML(name, 'remove', value)
238  else:
239  if name not in self.variables:
240  self.declare(name, self._guessType(name), False)
241  self.variables[name].remove(value, self.separator, regexp)
def EnvConfig.Control.Environment.remove_regexp (   self,
  name,
  value 
)

Definition at line 242 of file Control.py.

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

Definition at line 124 of file Control.py.

125  def search(self, varName, expr, regExp=False):
126  '''Searches in a variable for a value.'''
127  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 246 of file Control.py.

247  def searchFile(self, filename, varName):
248  '''Searches for appearance of variable in a file.'''
249  XMLFile = xmlModule.XMLFile()
250  variable = XMLFile.variable(filename, name=varName)
251  return variable
def EnvConfig.Control.Environment.set (   self,
  name,
  value 
)
Sets a single variable - overrides any previous value!

Definition at line 191 of file Control.py.

192  def set(self, name, value):
193  '''Sets a single variable - overrides any previous value!'''
194  name = str(name)
195  if self.asWriter:
196  self._writeVarToXML(name, 'set', value)
197  else:
198  if name not in self.variables:
199  self.declare(name, self._guessType(name), False)
200  self.variables[name].set(value, self.separator, self.variables)
def EnvConfig.Control.Environment.startXMLinput (   self)
Renew writer for new input.

Definition at line 275 of file Control.py.

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

Definition at line 225 of file Control.py.

226  def unset(self, name, value=None):# pylint: disable=W0613
227  '''Unsets a single variable to an empty value - overrides any previous value!'''
228  if self.asWriter:
229  self._writeVarToXML(name, 'unset', '')
230  else:
231  if name in self.variables:
232  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 117 of file Control.py.

118  def var(self, name):
119  '''Gets a single variable. If not available then tries to load from system.'''
120  if name in self.variables:
121  return self.variables[name]
122  else:
123  return os.environ[name]
def EnvConfig.Control.Environment.vars (   self,
  strings = True 
)
returns dictionary of all variables optionally converted to string

Definition at line 104 of file Control.py.

105  def vars(self, strings=True):
106  '''returns dictionary of all variables optionally converted to string'''
107  if strings:
108  return dict([(n, v.value(True))
109  for n, v in self.variables.items()
110  if n != '.'])
111  else:
112  # clone the dictionary to remove the internal special var '.'
113  vars_ = dict(self.variables)
114  if '.' in vars_:
115  del vars_['.']
116  return vars_
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 285 of file Control.py.

286  def writeToFile(self, fileName, shell='sh'):
287  '''Creates an output file with a specified name to be used for setting variables by sourcing this file'''
288  f = open(fileName, 'w')
289  if shell == 'sh':
290  f.write('#!/bin/bash\n')
291  for variable in self.variables:
292  if not self[variable].local:
293  f.write('export ' +variable+'='+self[variable].value(True, os.pathsep)+'\n')
294  elif shell == 'csh':
295  f.write('#!/bin/csh\n')
296  for variable in self.variables:
297  if not self[variable].local:
298  f.write('setenv ' +variable+' '+self[variable].value(True, os.pathsep)+'\n')
299  else:
300  f.write('')
301  f.write('REM This is an enviroment settings file generated on '+strftime("%a, %d %b %Y %H:%M:%S\n", gmtime()))
302  for variable in self.variables:
303  if not self[variable].local:
304  f.write('set '+variable+'='+self[variable].value(True, os.pathsep)+'\n')
305 
306  f.close()
307 
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 308 of file Control.py.

309  def writeToXMLFile(self, fileName):
310  '''Writes the current state of environment to a XML file.
311 
312  NOTE: There is no trace of actions taken, variables are written with a set action only.
313  '''
314  writer = xmlModule.XMLFile()
315  for varName in self.variables:
316  if varName == '.':
317  continue # this is an internal transient variable
318  writer.writeVar(varName, 'set', self.variables[varName].value(True, self.separator))
319  writer.writeToFile(fileName)
320 

Member Data Documentation

EnvConfig.Control.Environment._fileDirStack
private

Definition at line 57 of file Control.py.

EnvConfig.Control.Environment.actions

Definition at line 34 of file Control.py.

EnvConfig.Control.Environment.asWriter

Definition at line 49 of file Control.py.

EnvConfig.Control.Environment.loadedFiles

Definition at line 54 of file Control.py.

EnvConfig.Control.Environment.loadFromSystem

Definition at line 48 of file Control.py.

EnvConfig.Control.Environment.log

Definition at line 24 of file Control.py.

EnvConfig.Control.Environment.searchPath

Definition at line 30 of file Control.py.

EnvConfig.Control.Environment.separator

Definition at line 26 of file Control.py.

EnvConfig.Control.Environment.variables

Definition at line 46 of file Control.py.

EnvConfig.Control.Environment.writer

Definition at line 51 of file Control.py.


The documentation for this class was generated from the following file:
Generated at Wed Jun 4 2014 14:49:04 for Gaudi Framework, version v25r2 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004