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.]*)$")
188 if sys.platform !=
"win32":
194 _log.info(
"--> Including file '%s'", file)
196 _log.info(
"<-- End of file '%s'", file)
203 ifdef_skipping =
False
204 ifdef_skipping_level = 0
210 if l.startswith(
"#!"):
227 if not (m2
and m2.start() < m.start()):
230 l = l[: m.start()] + l[m.end() :]
234 directive_name = m.group(1)
235 directive_arg = m.group(2).strip()
236 if directive_name ==
"include":
237 included_file = directive_arg.strip(
"'\"")
239 elif directive_name ==
"units":
240 units_file = directive_arg.strip(
"'\"")
242 elif directive_name
in [
"ifdef",
"ifndef"]:
243 ifdef_skipping_level = ifdef_level
245 if directive_arg
in self.
defines:
246 ifdef_skipping = directive_name ==
"ifndef"
248 ifdef_skipping = directive_name ==
"ifdef"
249 elif directive_name ==
"else":
250 ifdef_skipping =
not ifdef_skipping
251 elif directive_name ==
"endif":
253 if ifdef_skipping
and ifdef_skipping_level == ifdef_level:
254 ifdef_skipping =
False
255 elif directive_name ==
"pragma":
256 if not directive_arg:
259 pragma = directive_arg.split()
260 if pragma[0] ==
"print":
262 if pragma[1].upper()
in [
"ON",
"TRUE",
"1"]:
267 _log.warning(
"unknown directive '%s'", directive_name)
278 l, l1 = l[: m.start()], l[m.end() :]
287 "End Of File reached before end of multi-line comment"
294 string_end = l.find(
'"')
296 statement += l[: string_end + 1]
297 l = l[string_end + 1 :]
303 string_start = l.find(
'"')
304 if string_start >= 0:
305 string_end = l.find(
'"', string_start + 1)
308 statement += l[: string_end + 1]
309 l = l[string_end + 1 :]
321 statement = l[i + 1 :]
324 if statement.lstrip().startswith(
"//"):
332 for line
in open(file):
334 line = line[: line.index(
"//")]
338 nunit, value = line.split(
"=")
339 factor, unit = nunit.split()
340 value = eval(value) / eval(factor)
341 self.
units[unit] = value
344 from GaudiKernel.Proxy.Configurable
import (
353 property, value = statement.split(
"=", 1)
356 if property[-1]
in [
"+",
"-"]:
358 property = property[:-1]
360 property = property.strip()
361 value = value.strip()
378 property =
".".join([w.strip()
for w
in property.split(
".")])
379 component, property = property.rsplit(
".", 1)
380 if component
in Configurable.allConfigurables:
381 cfg = Configurable.allConfigurables[component]
383 cfg = ConfigurableGeneric(component)
386 value = value.replace(
"true",
"True").replace(
"false",
"False")
389 if ":" in value
and not (
390 value[: value.index(
":")].count(
'"') % 2
391 or value[: value.index(
":")].count(
"'") % 2
394 value =
"{" + value[1:-1].replace(
"{",
"[").replace(
"}",
"]") +
"}"
396 value = value.replace(
"{",
"[").replace(
"}",
"]")
399 value = value.replace(
"\\",
"\\\\")
402 value.replace(
r"\\n",
r"\n").replace(
r"\\t",
r"\t").replace(
r'\\"',
r"\"")
407 (v
if i % 2
else re.sub(
r"\\[nt]",
" ", v))
408 for i, v
in enumerate(value.split(
'"'))
416 value = PropertyReference(m.group(1))
418 value = eval(value, self.
units)
423 if property
not in cfg.__slots__
and not hasattr(cfg, property):
425 lprop = property.lower()
426 for p
in cfg.__slots__:
427 if lprop == p.lower():
429 "property '%s' was requested for %s, but the correct spelling is '%s'",
439 if hasattr(cfg, property):
440 prop = getattr(cfg, property)
441 if isinstance(prop, dict):
447 setattr(cfg, property, value)
449 if hasattr(cfg, property):
450 prop = getattr(cfg, property)
451 if isinstance(prop, dict):
457 "key '%s' not in %s.%s", k, cfg.name(), property
465 "value '%s' not in %s.%s", k, cfg.name(), property
468 setattr(cfg, property, value)
484 with open(file)
as f:
485 code = compile(f.read(), file,
"exec")
486 exec(code, {
"__file__": file})
492 input = open(file,
"rb")
493 catalog = pickle.load(input)
494 _log.info(
"Unpickled %d configurables", len(catalog))
502 from GaudiKernel.Proxy.Configurable
import Configurable, ConfigurableGeneric
504 for property, value_repr
in data.items():
505 component, property = property.rsplit(
".", 1)
506 if component
in Configurable.allConfigurables:
507 cfg = Configurable.allConfigurables[component]
509 cfg = ConfigurableGeneric(component)
510 value = eval(value_repr)
511 setattr(cfg, property, value)
517 with open(filename)
as f:
521 _import_function_mapping = {
522 ".py": _import_python,
523 ".pkl": _import_pickle,
524 ".opts": _import_opts,
525 ".json": _import_json,
532 with open(filename)
as f:
535 _import_function_mapping[
".yaml"] = _import_yaml
536 _import_function_mapping[
".yml"] = _import_function_mapping[
".yaml"]
543 optsfile = os.path.expandvars(optsfile)
545 dummy, ext = os.path.splitext(optsfile)
546 if ext
in _import_function_mapping:
550 _log.info(
"--> Including file '%s'", optsfile)
552 _import_function_mapping[ext](optsfile)
553 _log.info(
"<-- End of file '%s'", optsfile)
555 raise ParserError(
"Unknown file type '%s' ('%s')" % (ext, optsfile))
567 unitsfile = os.path.expandvars(unitsfile)
570 _parser._include(unitsfile, _parser._parse_units)