2 Created on Jun 27, 2011
8 from time
import gmtime, strftime
14 '''object to hold settings of environment'''
16 def __init__(self, loadFromSystem=True, useAsWriter=False, searchPath=None):
17 '''Initial variables to be pushed and setup
19 append switch between append and prepend for initial variables.
20 loadFromSystem causes variable`s system value to be loaded on first encounter.
21 If useAsWriter == True than every change to variables is recorded to XML file.
22 reportLevel sets the level of messaging.
24 self.
log = logging.getLogger(
'Environment')
29 if searchPath
is None:
34 def addToSearchPath(n, _1, _2):
36 Add entries to the search path expanding variables inside.
39 entries.set(n, os.pathsep, environment=self.
variables)
40 self.searchPath.extend(entries)
46 self.
actions[
'set'] =
lambda n, v, _: self.
set(n, v)
52 self.
actions[
'search_path'] = addToSearchPath
69 dot.expandVars =
False
74 def _locate(self, filename, caller=None, hints=None):
76 Find 'filename' in the internal search path.
78 from os.path
import isabs, isfile, join, dirname, normpath, abspath
82 self.log.debug(
'looking for %s', filename)
85 elif type(hints)
is str:
90 localfile = join(calldir, filename)
91 self.log.debug(
'trying %s', localfile)
93 self.log.debug(
'OK (local file)')
96 hints = [join(calldir, hint)
for hint
in hints]
101 f = normpath(join(d, filename))
102 self.log.debug(
'trying %s', f)
105 f = (abspath(f)
for f
in candidates()
if isfile(f)).next()
108 except StopIteration:
109 from errno
import ENOENT
110 raise OSError(ENOENT,
'cannot find file in %r' % sp, filename)
113 '''returns dictionary of all variables optionally converted to string'''
115 return dict([(n, v.value(
True))
116 for n, v
in self.variables.items()
126 '''Gets a single variable. If not available then tries to load from system.'''
130 return os.environ[name]
132 def search(self, varName, expr, regExp=False):
133 '''Searches in a variable for a value.'''
138 Guess the type of the variable from its name: if the name contains
139 'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.
141 varname = varname.upper()
142 if 'PATH' in varname
or 'DIRS' in varname:
148 '''Creates an instance of new variable. It loads values from the OS if the variable is not local.'''
152 if not isinstance(local, bool):
153 if str(local).lower() ==
'true':
158 if name
in self.variables.keys():
162 if vartype.lower() ==
"list":
169 if vartype.lower() ==
"list":
176 a.set(os.environ[name], os.pathsep, environment=self.
variables)
182 '''Appends to an existing variable.'''
191 '''Prepends to an existing variable, or create a new one.'''
199 def set(self, name, value):
200 '''Sets a single variable - overrides any previous value!'''
210 '''Sets a single variable only if it is not already set!'''
224 v.set(os.environ[name], os.pathsep, environment=self.
variables)
234 '''Unsets a single variable to an empty value - overrides any previous value!'''
241 def remove(self, name, value, regexp=False):
242 '''Remove value from variable.'''
251 self.
remove(name, value,
True)
255 '''Searches for appearance of variable in a file.'''
257 variable = XMLFile.variable(filename, name=varName)
260 def loadXML(self, fileName=None, namespace='EnvSchema'):
261 '''Loads XML file for input variables.'''
263 fileName = self.
_locate(fileName)
265 self.log.debug(
'ignore %s: already loaded', fileName)
267 self.log.debug(
'loading %s', fileName)
268 self.loadedFiles.add(fileName)
271 self._fileDirStack.append(dot.value())
273 dot.set(os.path.dirname(fileName))
274 variables = XMLfile.variable(fileName, namespace=namespace)
275 for i, (action, args)
in enumerate(variables):
277 self.log.error(
'Node {0}: No action taken with var "{1}". Probably wrong action argument: "{2}".'.
format(i, args[0], action))
281 dot.set(self._fileDirStack.pop())
286 '''Renew writer for new input.'''
287 self.writer.resetWriter()
291 '''Finishes input of XML file and closes the file.'''
292 self.writer.writeToFile(outputFile)
296 '''Creates an output file with a specified name to be used for setting variables by sourcing this file'''
297 f = open(fileName,
'w')
299 f.write(
'#!/bin/bash\n')
301 if not self[variable].local:
302 f.write(
'export ' +variable+
'='+self[variable].
value(
True, os.pathsep)+
'\n')
304 f.write(
'#!/bin/csh\n')
306 if not self[variable].local:
307 f.write(
'setenv ' +variable+
' '+self[variable].
value(
True, os.pathsep)+
'\n')
310 f.write(
'REM This is an enviroment settings file generated on '+strftime(
"%a, %d %b %Y %H:%M:%S\n", gmtime()))
312 if not self[variable].local:
313 f.write(
'set '+variable+
'='+self[variable].
value(
True, os.pathsep)+
'\n')
319 '''Writes the current state of environment to a XML file.
321 NOTE: There is no trace of actions taken, variables are written with a set action only.
328 writer.writeToFile(fileName)
332 '''Loads all variables from the current system settings.'''
333 for k, v
in os.environ.items():
339 Call the variable processors on all the variables.
341 for v
in self.variables.values():
345 '''Returns a variable string with separator separator from the values list'''
349 stri = stri[0:len(stri)-1]
354 '''Writes single variable to XML file.'''
355 if isinstance(value, list):
357 self.writer.writeVar(name, action, value, vartype, local)
364 if key
in self.variables.keys():
365 self.log.warning(
'Addition canceled because of duplicate entry. Var: "%s" value: "%s".', key, value)
377 return item
in self.variables.keys()
380 return len(self.variables.keys())
def __delitem__(self, key)
def _concatenate(self, value)
def prepend(self, name, value)
def presetFromSystem(self)
def _guessType(self, varname)
def set(self, name, value)
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
def searchFile(self, filename, varName)
def append(self, name, value)
def __setitem__(self, key, value)
def remove_regexp(self, name, value)
def declare(self, name, vartype, local)
def __getitem__(self, key)
def __contains__(self, item)
def writeToXMLFile(self, fileName)
def default(self, name, value)