ensembl-hive-python3  2.7.0
utils.py
Go to the documentation of this file.
1 
2 # See the NOTICE file distributed with this work for additional information
3 # regarding copyright ownership.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 """
18 This module provide utility methods.
19 """
20 
21 import os
22 import sys
23 
24 from .process import BaseRunnable
25 
26 
27 def find_module(module_name):
28  """Find and instantiate a Runnable, given its name"""
29 
30  if os.path.exists(module_name):
31  module_name = os.path.normpath(module_name.rstrip(".py")).replace(os.path.sep, '.')
32 
33  module = None
34  def import_error(msg):
35  if msg[-1] != "\n":
36  msg += "\n"
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)
41 
42  # Import the whole module chain
43  try:
44  module = __import__(module_name)
45  except ImportError as e:
46  import_error("Cannot import '{0}' : {1}".format(module_name, e))
47 
48  # Traverse the namespaces down to the module
49  # e.g. If module_name is "eHive.examples.LongMult.AddTogether", module represents "LongMult" at this stage
50  for submodule in module_name.split('.')[1:]:
51  if hasattr(module, submodule):
52  module = getattr(module, submodule)
53  else:
54  import_error("Cannot find '{0}' in '{1}'".format(submodule, module))
55  # e.g. module now represents "AddTogether"
56 
57  if not hasattr(module, '__file__'):
58  import_error('"{0}" is a namespace, not a module'.format(module.__name__))
59 
60  # NB: We assume that the runnable has the same name as the file itself
61  class_name = module_name.split('.')[-1]
62 
63  # get the class in the module
64  if not hasattr(module, class_name):
65  # it could be a typo ... Let's print the available modules by decreasing distance to the required name
66  possible_modules = [_ for _ in dir(module) if isinstance(getattr(module, _), type) and issubclass(getattr(module, _), BaseRunnable)]
67  if possible_modules:
68  import difflib
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)))
73  else:
74  import_error("Warning: {} doesn't contain any Runnable classes".format(module_name))
75 
76  # Check that the class is a runnable
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__))
82 
83  return c
84 
eHive.utils.find_module
def find_module(module_name)
Find and instantiate a Runnable, given its name.
Definition: utils.py:28