17 _log = logging.getLogger(__name__)
21 def __init__(self, fmt=None, datefmt=None, prefix="# ", with_time=False):
22 logging.Formatter.__init__(self, fmt, datefmt)
27 fmsg = logging.Formatter.format(self, record)
30 prefix +=
"%f " % time.time()
31 if record.levelno >= logging.WARNING:
32 prefix += record.levelname +
": "
33 s =
"\n".join([prefix + line
for line
in fmsg.splitlines()])
39 logging.Filter.__init__(self, name)
45 return record.levelno >= self.
threshold or (
51 Decrease the printing_level of 'step' units. ( >0 means no print)
52 The level cannot go below 0, unless the force flag is set to True.
53 A negative value of the threshold disables subsequent "PrintOff"s.
65 Increase the printing_level of 'step' units. ( >0 means no print)
69 def disable(self, allowed=logging.WARNING):
73 def enable(self, allowed=logging.WARNING):
79 def __init__(self, stream=None, prefix=None, with_time=False):
82 logging.StreamHandler.__init__(self, stream)
95 Decrease the printing_level of 'step' units. ( >0 means no print)
96 The level cannot go below 0, unless the force flag is set to True.
97 A negative value of the threshold disables subsequent "PrintOff"s.
103 Increase the printing_level of 'step' units. ( >0 means no print)
110 def enable(self, allowed=logging.WARNING):
114 _consoleHandler =
None
118 global _consoleHandler
119 if _consoleHandler
is None:
121 prefix=prefix, stream=stream, with_time=with_time
123 elif prefix
is not None:
124 _consoleHandler.setPrefix(prefix)
125 return _consoleHandler
129 root_logger = logging.getLogger()
130 if not root_logger.handlers:
132 root_logger.setLevel(logging.WARNING)
133 if level
is not None:
134 root_logger.setLevel(level)
151 f = os.path.expandvars(f)
152 if os.path.isfile(f):
153 return os.path.realpath(f)
155 path = os.environ.get(
"JOBOPTSEARCHPATH",
"").split(os.pathsep)
157 candidates = [d
for d
in path
if os.path.isfile(os.path.join(d, f))]
159 raise ParserError(
"Cannot find '%s' in %s" % (f, path))
160 return os.path.realpath(os.path.join(candidates[0], f))
163 _included_files = set()
167 if f
in _included_files:
168 _log.warning(
"file '%s' already included, ignored.", f)
170 _included_files.add(f)
175 comment = re.compile(
r"(//.*)$")
178 comment_in_string = re.compile(
r'(["\']).*//.*\1')
179 directive = re.compile(
r"^\s*#\s*([\w!]+)\s*(.*)\s*$")
180 comment_ml = (re.compile(
r"/\*"), re.compile(
r"\*/"))
182 reference = re.compile(
r"^@([\w.]*)$")
192 _log.info(
"--> Including file '%s'", file)
194 _log.info(
"<-- End of file '%s'", file)
201 ifdef_skipping =
False
202 ifdef_skipping_level = 0
208 if l.startswith(
"#!"):
225 if not (m2
and m2.start() < m.start()):
228 l = l[: m.start()] + l[m.end() :]
232 directive_name = m.group(1)
233 directive_arg = m.group(2).strip()
234 if directive_name ==
"include":
235 included_file = directive_arg.strip(
"'\"")
237 elif directive_name ==
"units":
238 units_file = directive_arg.strip(
"'\"")
240 elif directive_name
in [
"ifdef",
"ifndef"]:
241 ifdef_skipping_level = ifdef_level
243 if directive_arg
in self.
defines:
244 ifdef_skipping = directive_name ==
"ifndef"
246 ifdef_skipping = directive_name ==
"ifdef"
247 elif directive_name ==
"else":
248 ifdef_skipping =
not ifdef_skipping
249 elif directive_name ==
"endif":
251 if ifdef_skipping
and ifdef_skipping_level == ifdef_level:
252 ifdef_skipping =
False
253 elif directive_name ==
"pragma":
254 if not directive_arg:
257 pragma = directive_arg.split()
258 if pragma[0] ==
"print":
260 if pragma[1].upper()
in [
"ON",
"TRUE",
"1"]:
265 _log.warning(
"unknown directive '%s'", directive_name)
276 l, l1 = l[: m.start()], l[m.end() :]
285 "End Of File reached before end of multi-line comment"
292 string_end = l.find(
'"')
294 statement += l[: string_end + 1]
295 l = l[string_end + 1 :]
301 string_start = l.find(
'"')
302 if string_start >= 0:
303 string_end = l.find(
'"', string_start + 1)
306 statement += l[: string_end + 1]
307 l = l[string_end + 1 :]
319 statement = l[i + 1 :]
322 if statement.lstrip().startswith(
"//"):
330 for line
in open(file):
332 line = line[: line.index(
"//")]
336 nunit, value = line.split(
"=")
337 factor, unit = nunit.split()
338 value = eval(value) / eval(factor)
339 self.
units[unit] = value
342 from GaudiKernel.Proxy.Configurable
import (
351 property, value = statement.split(
"=", 1)
354 if property[-1]
in [
"+",
"-"]:
356 property = property[:-1]
358 property = property.strip()
359 value = value.strip()
376 property =
".".join([w.strip()
for w
in property.split(
".")])
377 component, property = property.rsplit(
".", 1)
378 if component
in Configurable.allConfigurables:
379 cfg = Configurable.allConfigurables[component]
381 cfg = ConfigurableGeneric(component)
384 value = value.replace(
"true",
"True").replace(
"false",
"False")
387 if ":" in value
and not (
388 value[: value.index(
":")].count(
'"') % 2
389 or value[: value.index(
":")].count(
"'") % 2
392 value =
"{" + value[1:-1].replace(
"{",
"[").replace(
"}",
"]") +
"}"
394 value = value.replace(
"{",
"[").replace(
"}",
"]")
397 value = value.replace(
"\\",
"\\\\")
400 value.replace(
r"\\n",
r"\n").replace(
r"\\t",
r"\t").replace(
r'\\"',
r"\"")
405 (v
if i % 2
else re.sub(
r"\\[nt]",
" ", v))
406 for i, v
in enumerate(value.split(
'"'))
414 value = PropertyReference(m.group(1))
416 value = eval(value, self.
units)
421 if property
not in cfg.__slots__
and not hasattr(cfg, property):
423 lprop = property.lower()
424 for p
in cfg.__slots__:
425 if lprop == p.lower():
427 "property '%s' was requested for %s, but the correct spelling is '%s'",
437 if hasattr(cfg, property):
438 prop = getattr(cfg, property)
439 if isinstance(prop, dict):
445 setattr(cfg, property, value)
447 if hasattr(cfg, property):
448 prop = getattr(cfg, property)
449 if isinstance(prop, dict):
455 "key '%s' not in %s.%s", k, cfg.name(), property
463 "value '%s' not in %s.%s", k, cfg.name(), property
466 setattr(cfg, property, value)
482 with open(file)
as f:
483 code = compile(f.read(), file,
"exec")
484 exec(code, {
"__file__": file})
490 input = open(file,
"rb")
491 catalog = pickle.load(input)
492 _log.info(
"Unpickled %d configurables", len(catalog))
500 from GaudiKernel.Proxy.Configurable
import Configurable, ConfigurableGeneric
502 for property, value_repr
in data.items():
503 component, property = property.rsplit(
".", 1)
504 if component
in Configurable.allConfigurables:
505 cfg = Configurable.allConfigurables[component]
507 cfg = ConfigurableGeneric(component)
508 value = eval(value_repr)
509 setattr(cfg, property, value)
515 with open(filename)
as f:
519 _import_function_mapping = {
520 ".py": _import_python,
521 ".pkl": _import_pickle,
522 ".opts": _import_opts,
523 ".json": _import_json,
530 with open(filename)
as f:
533 _import_function_mapping[
".yaml"] = _import_yaml
534 _import_function_mapping[
".yml"] = _import_function_mapping[
".yaml"]
541 optsfile = os.path.expandvars(optsfile)
543 dummy, ext = os.path.splitext(optsfile)
544 if ext
in _import_function_mapping:
548 _log.info(
"--> Including file '%s'", optsfile)
550 _import_function_mapping[ext](optsfile)
551 _log.info(
"<-- End of file '%s'", optsfile)
553 raise ParserError(
"Unknown file type '%s' ('%s')" % (ext, optsfile))
565 unitsfile = os.path.expandvars(unitsfile)
568 _parser._include(unitsfile, _parser._parse_units)