python import_module函数没有加载包

时间:2016-08-08 17:41:30

标签: python python-import

我有以下openstack集会代码,它使用以下函数从给定路径动态加载python模块。

def load_plugins(dir_or_file):
   if os.path.isdir(dir_or_file):
      directory = dir_or_file
      LOG.info(_("Loading plugins from directories %s/*") %
             directory.rstrip("/"))

      to_load = []
      for root, dirs, files in os.walk(directory, followlinks=True):
          to_load.extend((plugin[:-3], root)
                         for plugin in files if plugin.endswith(".py"))
      for plugin, directory in to_load:
         if directory not in sys.path:
            sys.path.append(directory)

         fullpath = os.path.join(directory, plugin)
         try:
            fp, pathname, descr = imp.find_module(plugin, [directory])
            imp.load_module(plugin, fp, pathname, descr)
            fp.close()
            LOG.info(_("\t Loaded module with plugins: %s.py") % fullpath)
         except Exception as e:
            LOG.warning(
                "\t Failed to load module with plugins %(path)s.py: %(e)s"
                % {"path": fullpath, "e": e})
            if logging.is_debug():
                LOG.exception(e)
   elif os.path.isfile(dir_or_file):
      plugin_file = dir_or_file
      LOG.info(_("Loading plugins from file %s") % plugin_file)
      if plugin_file not in sys.path:
         sys.path.append(plugin_file)
      try:
         plugin_name = os.path.splitext(plugin_file.split("/")[-1])[0]
         imp.load_source(plugin_name, plugin_file)
         LOG.info(_("\t Loaded module with plugins: %s.py") % plugin_name)
      except Exception as e:
         LOG.warning(_(
            "\t Failed to load module with plugins %(path)s: %(e)s")
            % {"path": plugin_file, "e": e})
         if logging.is_debug():
            LOG.exception(e)

直到2天前,这个工作非常好。现在我没有收到错误,但它也没有加载任何类。 我只打印了第一个日志信息并将其打印出来,同时查找已加载的类失败。从下面,ensure_plugins_are_loaded在内部调用函数。

 File "<decorator-gen-3>", line 2, in _run
 File "build/bdist.linux-x86_64/egg/rally/plugins/__init__.py", in    ensure_plugins_are_loaded
 File "build/bdist.linux-x86_64/egg/rally/task/engine.py",  in validate

更新1

我尝试调用一个简单的importlib.import_module('/ opt / plugins')。仍然没有从import_module抛出错误但python仍然找不到加载的模块。我试图找到使用subs = cls。子类()的模块,它扩展了给定的子类。

更新2

我也尝试使用相同的代码而不创建bdist_egg包。 刚做过

  

python setup.py develop

它工作正常。所以我不确定与bdist_egg一起使用时会出现什么问题。

0 个答案:

没有答案