14 Generate _confDb.py files for ConfigurableUser classes. 16 from __future__
import division
23 from pprint
import pformat
27 logging.VERBOSE = (logging.INFO + logging.DEBUG) // 2
28 logging.addLevelName(logging.VERBOSE,
"VERBOSE")
29 logging.verbose =
lambda msg, *args, **kwargs: \
30 logging.log(logging.VERBOSE, msg, *args, **kwargs)
35 Check if any of the class names in 'basenames' is anywhere in the base 36 classes of the class 'derived'. 37 If 'derived' _is_ one in 'basenames', returns False. 39 'basenames' can be a string or an iterable (of strings). 41 if isinstance(basenames, str):
42 basenames = (basenames, )
43 for b
in derived.__bases__:
44 if b.__name__
in basenames:
54 Equivalent to GaudiKernel.ConfigurableDb.loadConfigurableDb(), but does a 55 deep search and executes the '*.confdb' files instead of importing them. 57 log = GaudiKernel.ConfigurableDb.log
58 from os.path
import join
as path_join
64 f
for f
in glob(path_join(path,
'*',
'*.confdb'))
68 pathlist = os.getenv(
"LD_LIBRARY_PATH",
"").split(os.pathsep)
69 for path
in filter(os.path.isdir, pathlist):
72 path_join(path, f)
for f
in os.listdir(path)
73 if f.endswith(
'.confdb')
77 for confDb
in confDbFiles:
78 log.debug(
"\t-loading [%s]..." % confDb)
80 cfgDb._loadModule(confDb)
81 except Exception
as err:
84 log.warning(
"Could not load file [%s] !", confDb)
85 log.warning(
"Reason: %s", err)
92 Find in the module 'modulename' all the classes that derive from ConfigurableUser. 93 Return the list of the names. 94 The flag mayNotExist is used to choose the level of the logging message in case 95 the requested module does not exist. 98 oldpath = list(sys.path)
100 moduleelements = modulename.split(
'.')
101 if len(moduleelements) > 1:
102 moddir = os.sep.join([root] + moduleelements[:-1])
106 shortmodname = moduleelements[-1]
108 if not os.path.exists(os.path.join(moddir, shortmodname) +
".py"):
109 msg =
"Module %s does not exist" % modulename
117 sys.path.insert(0, moddir)
118 logging.verbose(
"sys.path prepended with %r", sys.path[0])
120 logging.info(
"Looking for ConfigurableUser in %r", modulename)
123 logging.verbose(
"importing %s", shortmodname)
124 exec (
"import %s as mod" % shortmodname, g, l)
127 logging.verbose(
"restoring old sys.path")
130 if "__all__" in dir(mod)
and mod.__all__:
133 all = [n
for n
in dir(mod)
if not n.startswith(
"_")]
136 cfg = cfgDb.get(name)
137 if cfg
and cfg[
"module"] != modulename:
139 logging.verbose(
"Object %r already found in module %r", name,
142 t = getattr(mod, name)
144 t, (
'ConfigurableUser',
'SuperAlgorithm')):
146 logging.verbose(
"Found %r", result)
151 from optparse
import OptionParser
152 parser = OptionParser(
153 prog=os.path.basename(sys.argv[0]),
154 usage=
"%prog [options] <PackageName> [<Module1> ...]")
161 "output file for confDb data [default = '../genConf/<PackageName>_user_confDb.py']." 168 help=
"root directory of the python modules [default = '../python'].")
173 help=
"print some debugging information")
177 help=
"print more debugging information")
178 parser.set_defaults(root=os.path.join(
"..",
"python"))
180 opts, args = parser.parse_args()
183 log_level = logging.DEBUG
185 log_level = logging.VERBOSE
187 log_level = logging.INFO
if os.environ.get(
188 'VERBOSE')
else logging.WARNING
190 format=
"%(levelname)s: %(message)s",
195 parser.error(
"PackageName is required")
197 package_name = args.pop(0)
199 usingConvention =
False 202 args = [package_name +
".Configuration"]
203 usingConvention =
True 205 genConfDir = os.path.join(
"..", os.environ.get(
"CMTCONFIG",
""),
"genConf")
206 if not os.path.exists(genConfDir):
207 genConfDir = os.path.join(
"..",
"genConf")
210 outputfile = os.path.join(genConfDir, package_name +
'_user.confdb')
212 outputfile = opts.output
217 import Gaudi.Configurables
218 Gaudi.Configurables.ignoreMissingConfigurables =
True 227 sys.path.insert(0, genConfDir)
228 sys.path.insert(0, os.path.join(
"..",
"python"))
229 localConfDb = os.path.join(genConfDir, package_name,
230 package_name +
'.confdb')
231 if os.path.exists(localConfDb):
232 cfgDb._loadModule(localConfDb)
234 package_module = __import__(package_name)
235 package_module.__path__.insert(
236 0, os.path.join(genConfDir, package_name))
246 mod, root=opts.root, mayNotExist=usingConvention)
250 "Cannot import module %r:\n%s", mod,
251 traceback.format_exc().rstrip())
258 configurable=m, package=
'None', module=
'None', lib=
'None')
259 elif not usingConvention:
261 "Specified module %r does not contain ConfigurableUser specializations",
265 logging.info(
"ConfigurableUser found:\n%s", pformat(cus))
267 output =
"""## -*- ascii -*- 268 # db file automatically generated by %s on: %s 269 """ % (parser.prog, time.asctime())
273 output +=
"%s %s %s\n" % (mod,
'None', cu)
276 output +=
"## %s\n" % package_name
277 elif usingConvention:
278 logging.info(
"No ConfigurableUser found")
279 output = (
"# db file automatically generated by %s on: %s\n" 280 "# No ConfigurableUser specialization in %s\n") % (
281 parser.prog, time.asctime(), package_name)
283 logging.error(
"No ConfigurableUser specialization found")
287 output_dir = os.path.dirname(outputfile)
289 logging.info(
"Creating directory %r", output_dir)
290 os.makedirs(output_dir, 0o755)
291 except OSError
as err:
293 if err.errno == errno.EEXIST:
300 logging.verbose(
"Writing confDb data to %r", outputfile)
301 open(outputfile,
"w").write(output)
305 if __name__ ==
'__main__':
def getConfigurableUsers(modulename, root, mayNotExist=False)
def _inheritsfrom(derived, basenames)