| # Gaudi Framework, version v25r0 |

Home |  | Generated: Mon Feb 17 2014

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- Class List
- Class Index
- Class Hierarchy
- Class Members

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:
[legend]
Collaboration diagram for EnvConfig.Control.Environment:
[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 360 of file Control.py.

360
361 def __contains__(self, item):
362 return item in self.variables.keys()

def EnvConfig.Control.Environment.__delitem__ | ( |  | self,
|  |  | key
| ) |  |

Definition at line 353 of file Control.py.

353
354 def __delitem__(self, key):
355 del self.variables[key]

def EnvConfig.Control.Environment.__getitem__ | ( |  | self,
|  |  | key
| ) |  |

Definition at line 344 of file Control.py.

344
345 def __getitem__(self, key):
346 return self.variables[key]

def EnvConfig.Control.Environment.__iter__ | ( |  | self | ) |

Definition at line 356 of file Control.py.

356
357 def __iter__(self):
358 for i in self.variables:
359 yield i

def EnvConfig.Control.Environment.__len__ | ( |  | self | ) |

Definition at line 363 of file Control.py.

363
364 def __len__(self):
365 return len(self.variables.keys())
366

def EnvConfig.Control.Environment.__setitem__ | ( |  | self,
|  |  | key,
|  |  | value
| ) |  |

Definition at line 347 of file Control.py.

347
348 def __setitem__(self, key, value):
349 if key in self.variables.keys():
350 self.log.warning('Addition canceled because of duplicate entry. Var: "%s" value: "%s".', key, value)
351 else:
352 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 328 of file Control.py.

328
329 def _concatenate(self, value):
330 '''Returns a variable string with separator separator from the values list'''
331 stri = ""
332 for it in value:
333 stri += it + self.separator
334 stri = stri[0:len(stri)-1]
335 return stri
336

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

122
123 def _guessType(self, varname):
124 '''
125 Guess the type of the variable from its name: if the name contains
126 'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.
127 '''
128 varname = varname.upper() # make the comparison case insensitive
129 if 'PATH' in varname or 'DIRS' in varname:
130 return 'list'
131 else:
132 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 337 of file Control.py.

337
338 def _writeVarToXML(self, name, action, value, vartype='list', local='false'):
339 '''Writes single variable to XML file.'''
340 if isinstance(value, list):
341 value = self._concatenate(value)
342 self.writer.writeVar(name, action, value, vartype, local)
343

def EnvConfig.Control.Environment.append | ( |  | self,
|  |  | name,
|  |  | value
| ) |  |

    Appends to an existing variable.

Definition at line 167 of file Control.py.

167
168 def append(self, name, value):
169 '''Appends to an existing variable.'''
170 if self.asWriter:
171 self._writeVarToXML(name, 'append', value)
172 else:
173 if name not in self.variables:
174 self.declare(name, self._guessType(name), False)
175 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 133 of file Control.py.

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

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

274
275 def finishXMLinput(self, outputFile = ''):
276 '''Finishes input of XML file and closes the file.'''
277 self.writer.writeToFile(outputFile)
278

def EnvConfig.Control.Environment.loadXML | ( |  | self,
|  |  | fileName = `None`,
|  |  | namespace = `'EnvSchema'`
| ) |  |

    Loads XML file for input variables.

Definition at line 246 of file Control.py.

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

def EnvConfig.Control.Environment.prepend | ( |  | self,
|  |  | name,
|  |  | value
| ) |  |

    Prepends to an existing variable, or create a new one.

Definition at line 176 of file Control.py.

176
177 def prepend(self, name, value):
178 '''Prepends to an existing variable, or create a new one.'''
179 if self.asWriter:
180 self._writeVarToXML(name, 'prepend', value)
181 else:
182 if name not in self.variables:
183 self.declare(name, self._guessType(name), False)
184 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 315 of file Control.py.

315
316 def presetFromSystem(self):
317 '''Loads all variables from the current system settings.'''
318 for k, v in os.environ.items():
319 if k not in self.variables:
320 self.set(k, v)

def EnvConfig.Control.Environment.process | ( |  | self | ) |

    Call the variable processors on all the variables.

Definition at line 321 of file Control.py.

321
322 def process(self):
323 '''
324 Call the variable processors on all the variables.
325 '''
326 for v in self.variables.values():
327 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 227 of file Control.py.

227
228 def remove(self, name, value, regexp=False):
229 '''Remove value from variable.'''
230 if self.asWriter:
231 self._writeVarToXML(name, 'remove', value)
232 else:
233 if name not in self.variables:
234 self.declare(name, self._guessType(name), False)
235 self.variables[name].remove(value, self.separator, regexp)

def EnvConfig.Control.Environment.remove_regexp | ( |  | self,
|  |  | name,
|  |  | value
| ) |  |

Definition at line 236 of file Control.py.

236
237 def remove_regexp(self, name, value):
238 self.remove(name, value, True)
239

def EnvConfig.Control.Environment.search | ( |  | self,
|  |  | varName,
|  |  | expr,
|  |  | regExp = `False`
| ) |  |

    Searches in a variable for a value.

Definition at line 118 of file Control.py.

118
119 def search(self, varName, expr, regExp=False):
120 '''Searches in a variable for a value.'''
121 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 240 of file Control.py.

240
241 def searchFile(self, filename, varName):
242 '''Searches for appearance of variable in a file.'''
243 XMLFile = xmlModule.XMLFile()
244 variable = XMLFile.variable(filename, name=varName)
245 return variable

def EnvConfig.Control.Environment.set | ( |  | self,
|  |  | name,
|  |  | value
| ) |  |

    Sets a single variable - overrides any previous value!

Definition at line 185 of file Control.py.

185
186 def set(self, name, value):
187 '''Sets a single variable - overrides any previous value!'''
188 name = str(name)
189 if self.asWriter:
190 self._writeVarToXML(name, 'set', value)
191 else:
192 if name not in self.variables:
193 self.declare(name, self._guessType(name), False)
194 self.variables[name].set(value, self.separator, self.variables)

def EnvConfig.Control.Environment.startXMLinput | ( |  | self | ) |

    Renew writer for new input.

Definition at line 269 of file Control.py.

269
270 def startXMLinput(self):
271 '''Renew writer for new input.'''
272 self.writer.resetWriter()
273

def EnvConfig.Control.Environment.unset | ( |  | self,
|  |  | name,
|  |  | value = `None`
| ) |  |

    Unsets a single variable to an empty value - overrides any previous value!

Definition at line 219 of file Control.py.

219
220 def unset(self, name, value=None):# pylint: disable=W0613
221 '''Unsets a single variable to an empty value - overrides any previous value!'''
222 if self.asWriter:
223 self._writeVarToXML(name, 'unset', '')
224 else:
225 if name in self.variables:
226 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 111 of file Control.py.

111
112 def var(self, name):
113 '''Gets a single variable. If not available then tries to load from system.'''
114 if name in self.variables:
115 return self.variables[name]
116 else:
117 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.

104
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)) for n, v in self.variables.items()])
109 else:
110 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 279 of file Control.py.

279
280 def writeToFile(self, fileName, shell='sh'):
281 '''Creates an output file with a specified name to be used for setting variables by sourcing this file'''
282 f = open(fileName, 'w')
283 if shell == 'sh':
284 f.write('#!/bin/bash\n')
285 for variable in self.variables:
286 if not self[variable].local:
287 f.write('export ' +variable+'='+self[variable].value(True, os.pathsep)+'\n')
288 elif shell == 'csh':
289 f.write('#!/bin/csh\n')
290 for variable in self.variables:
291 if not self[variable].local:
292 f.write('setenv ' +variable+' '+self[variable].value(True, os.pathsep)+'\n')
293 else:
294 f.write('')
295 f.write('REM This is an enviroment settings file generated on '+strftime("%a, %d %b %Y %H:%M:%S\n", gmtime()))
296 for variable in self.variables:
297 if not self[variable].local:
298 f.write('set '+variable+'='+self[variable].value(True, os.pathsep)+'\n')
299
300 f.close()
301

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

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

## 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:

- /afs/cern.ch/sw/Gaudi/releases/GAUDI/GAUDI_v25r0/cmake/EnvConfig/Control.py