18 This module provide utility methods.
24 from .process
import BaseRunnable
28 """Find and instantiate a Runnable, given its name"""
30 if os.path.exists(module_name):
31 module_name = os.path.normpath(module_name.rstrip(
".py")).replace(os.path.sep,
'.')
34 def import_error(msg):
37 if (module
is not None)
and hasattr(module,
'__file__'):
38 msg += module.__name__ +
" is in " + module.__file__ +
"\n"
39 msg +=
"sys.path is " + str(sys.path)
40 raise ImportError(msg)
44 module = __import__(module_name)
45 except ImportError
as e:
46 import_error(
"Cannot import '{0}' : {1}".format(module_name, e))
50 for submodule
in module_name.split(
'.')[1:]:
51 if hasattr(module, submodule):
52 module = getattr(module, submodule)
54 import_error(
"Cannot find '{0}' in '{1}'".format(submodule, module))
57 if not hasattr(module,
'__file__'):
58 import_error(
'"{0}" is a namespace, not a module'.format(module.__name__))
61 class_name = module_name.split(
'.')[-1]
64 if not hasattr(module, class_name):
66 possible_modules = [_
for _
in dir(module)
if isinstance(getattr(module, _), type)
and issubclass(getattr(module, _), BaseRunnable)]
69 possible_modules.sort(key=
lambda s: difflib.SequenceMatcher(a=class_name, b=s, autojunk=
False).ratio(), reverse=
True)
70 s =
"No class named '{0}' in the module '{1}'.\n"
71 s +=
"Warning: {1} contains {2} Runnable classes ({3}). Should one of them be renamed ?"
72 import_error(s.format(class_name, module_name, len(possible_modules),
', '.join(
'"%s"' % _
for _
in possible_modules)))
74 import_error(
"Warning: {} doesn't contain any Runnable classes".format(module_name))
77 c = getattr(module, class_name)
78 if not isinstance(c, type):
79 import_error(
"{0} (found in {1}) is not a class but a {2}".format(class_name, module.__file__, type(c)))
80 if not issubclass(c, BaseRunnable):
81 import_error(
"{0} (found in {1}) is not a sub-class of eHive.BaseRunnable".format(class_name, module.__file__))