5 _log = logging.getLogger(__name__)
8 def __init__(self, fmt=None, datefmt=None, prefix = "# ", with_time = False):
9 logging.Formatter.__init__(self, fmt, datefmt)
13 fmsg = logging.Formatter.format(self, record)
16 prefix +=
'%f ' % time.time()
17 if record.levelno >= logging.WARNING:
18 prefix += record.levelname +
": "
19 s =
"\n".join([ prefix + line
20 for line
in fmsg.splitlines() ])
25 logging.Filter.__init__(self, name)
31 def printOn(self, step = 1, force = False):
33 Decrease the printing_level of 'step' units. ( >0 means no print)
34 The level cannot go below 0, unless the force flag is set to True.
35 A negative value of the threshold disables subsequent "PrintOff"s.
46 Increase the printing_level of 'step' units. ( >0 means no print)
49 def disable(self, allowed = logging.WARNING):
52 def enable(self, allowed = logging.WARNING):
57 def __init__(self, stream = None, prefix = None, with_time = False):
60 logging.StreamHandler.__init__(self, stream)
68 self._formatter.prefix = prefix
69 def printOn(self, step = 1, force = False):
71 Decrease the printing_level of 'step' units. ( >0 means no print)
72 The level cannot go below 0, unless the force flag is set to True.
73 A negative value of the threshold disables subsequent "PrintOff"s.
75 self._filter.printOn(step, force)
78 Increase the printing_level of 'step' units. ( >0 means no print)
80 self._filter.printOff(step)
81 def disable(self, allowed = logging.WARNING):
82 self._filter.disable(allowed)
83 def enable(self, allowed = logging.WARNING):
84 self._filter.enable(allowed)
86 _consoleHandler =
None
88 global _consoleHandler
89 if _consoleHandler
is None:
90 _consoleHandler =
ConsoleHandler(prefix = prefix, stream = stream, with_time = with_time)
91 elif prefix
is not None:
92 _consoleHandler.setPrefix(prefix)
93 return _consoleHandler
96 root_logger = logging.getLogger()
97 if not root_logger.handlers:
99 root_logger.setLevel(logging.WARNING)
100 if level
is not None:
101 root_logger.setLevel(level)
113 f = os.path.expandvars(f)
114 if os.path.isfile(f):
115 return os.path.realpath(f)
117 path = os.environ.get(
'JOBOPTSEARCHPATH',
'').split(os.pathsep)
119 candidates = [d
for d
in path
if os.path.isfile(os.path.join(d,f))]
121 raise ParserError(
"Cannot find '%s' in %s" % (f,path))
122 return os.path.realpath(os.path.join(candidates[0],f))
124 _included_files = set()
126 if f
in _included_files:
127 _log.warning(
"file '%s' already included, ignored.", f)
129 _included_files.add(f)
133 comment = re.compile(
r'(//.*)$')
136 comment_in_string = re.compile(
r'(["\']).*//.*\1')
137 directive = re.compile(
r'^\s*#\s*([\w!]+)\s*(.*)\s*$')
138 comment_ml = ( re.compile(
r'/\*'), re.compile(
r'\*/') )
140 reference = re.compile(
r'^@([\w.]*)$')
146 if sys.platform !=
'win32':
147 self.defines[
"WIN32" ] =
True
149 def _include(self,file,function):
152 _log.info(
"--> Including file '%s'", file)
154 _log.info(
"<-- End of file '%s'", file)
156 def parse(self,file):
161 ifdef_skipping =
False
162 ifdef_skipping_level = 0
166 if l.startswith(
"#!"):
175 m = self.comment.search(l)
178 m2 = self.comment_in_string.search(l)
181 if not ( m2
and m2.start() < m.start() ):
184 l = l[:m.start()]+l[m.end():]
186 m = self.directive.search(l)
188 directive_name = m.group(1)
189 directive_arg = m.group(2).strip()
190 if directive_name ==
"include":
191 included_file = directive_arg.strip(
"'\"")
193 elif directive_name ==
"units":
194 units_file = directive_arg.strip(
"'\"")
195 self._include(units_file,self._parse_units)
196 elif directive_name
in [
"ifdef",
"ifndef"]:
197 ifdef_skipping_level = ifdef_level
199 if directive_arg
in self.defines:
200 ifdef_skipping = directive_name ==
"ifndef"
202 ifdef_skipping = directive_name ==
"ifdef"
203 elif directive_name ==
"else":
204 ifdef_skipping =
not ifdef_skipping
205 elif directive_name ==
"endif":
207 if ifdef_skipping
and ifdef_skipping_level == ifdef_level:
208 ifdef_skipping =
False
209 elif directive_name ==
"pragma":
210 if not directive_arg:
213 pragma = directive_arg.split()
214 if pragma[0] ==
"print":
216 if pragma[1].upper()
in [
"ON",
"TRUE",
"1" ]:
221 _log.warning(
"unknown directive '%s'", directive_name)
230 m = self.comment_ml[0].search(l)
232 l,l1 = l[:m.start()],l[m.end():]
233 m = self.comment_ml[1].search(l1)
238 m = self.comment_ml[1].search(l1)
240 raise ParserError(
"End Of File reached before end of multi-line comment")
243 if self.statement_sep
in l:
244 i = l.index(self.statement_sep)
246 self._eval_statement(statement.strip().replace(
"\n",
"\\n"))
250 if statement.lstrip().startswith(
"//"):
257 def _parse_units(self,file):
258 for line
in open(file):
260 line = line[:line.index(
'//')]
264 nunit, value = line.split(
'=')
265 factor, unit = nunit.split()
266 value = eval(value)/eval(factor)
267 self.units[unit] = value
269 def _eval_statement(self,statement):
270 from GaudiKernel.Proxy.Configurable
import (ConfigurableGeneric,
274 _log.info(
"%s%s", statement, self.statement_sep)
276 property,value = statement.split(
"=",1)
279 if property[-1]
in [
"+",
"-" ]:
281 property = property[:-1]
283 property = property.strip()
284 value = value.strip()
301 property =
'.'.join([w.strip()
for w
in property.split(
'.')])
302 component, property = property.rsplit(
'.',1)
303 if component
in Configurable.allConfigurables:
304 cfg = Configurable.allConfigurables[component]
306 cfg = ConfigurableGeneric(component)
309 value = value.replace(
'true',
'True').replace(
'false',
'False')
312 if ':' in value
and not ( value[:value.index(
':')].count(
'"')%2
or value[:value.index(
':')].count(
"'")%2 ) :
314 value =
'{'+value[1:-1].replace(
'{',
'[').replace(
'}',
']')+
'}'
316 value = value.replace(
'{',
'[').replace(
'}',
']')
319 value = value.replace(
'\\',
'\\\\')
321 value = (value.replace(
r"\\n",
r"\n")
322 .replace(
r"\\t",
r"\t")
323 .replace(
r'\\"',
r'\"'))
325 value =
'"'.join([(v
if i % 2
else re.sub(
r'\\[nt]',
' ', v))
326 for i, v
in enumerate(value.split(
'"'))])
329 m = self.reference.match(value)
332 value = PropertyReference(m.group(1))
334 value = eval(value,self.units)
339 if property
not in cfg.__slots__
and not hasattr(cfg,property):
341 lprop = property.lower()
342 for p
in cfg.__slots__:
343 if lprop == p.lower():
344 _log.warning(
"property '%s' was requested for %s, but the correct spelling is '%s'", property, cfg.name(), p)
350 if hasattr(cfg,property):
351 prop = getattr(cfg,property)
352 if type(prop) == dict:
358 setattr(cfg,property,value)
360 if hasattr(cfg,property):
361 prop = getattr(cfg,property)
362 if type(prop)
is dict:
367 _log.warning(
"key '%s' not in %s.%s", k, cfg.name(), property)
373 _log.warning(
"value '%s' not in %s.%s", k, cfg.name(), property)
375 setattr(cfg,property,value)
391 input = open(file,
'rb')
392 catalog = pickle.load(input)
393 _log.info(
'Unpickled %d configurables', len(catalog))
398 _import_function_mapping = {
399 ".py" : _import_python,
400 ".pkl" : _import_pickle,
401 ".opts" : _import_opts,
406 optsfile = os.path.expandvars(optsfile)
408 dummy, ext = os.path.splitext(optsfile)
409 if ext
in _import_function_mapping:
413 _log.info(
"--> Including file '%s'", optsfile)
415 _import_function_mapping[ext](optsfile)
416 _log.info(
"<-- End of file '%s'", optsfile)
418 raise ParserError(
"Unknown file type '%s' ('%s')" % (ext,optsfile))
427 unitsfile = os.path.expandvars(unitsfile)
430 _parser._include(unitsfile, _parser._parse_units)
StatusCode parse(GaudiUtils::HashMap< K, V > &result, const std::string &input)
Basic parser for the types of HashMap used in DODBasicMapper.
def __init__(self, new_path)
def importOptions(optsfile)
def setPrefix(self, prefix)
def InstallRootLoggingHandler
def importUnits(unitsfile)
Import a file containing declaration of units.