Problems when converting from imp to importlib in python 3.4

天大地大妈咪最大 提交于 2019-12-12 10:53:50

问题


I've made a Python application which can load plugins. These plugins are loaded based on a name and path.

I am currently using

pluginModule = imp.load_source(pluginModuleName,  pluginModulePath)

and then getting a class instance in the module this way

# Load the module class and initialize it.
if hasattr(pluginModule, pluginClassName):
  try:
    pluginClassInst = getattr(pluginModule, pluginClassName)()
  except Exception as e:
    errorMsg = ('In plugin module [{}], {}'.format(os.path.basename(pluginModulePath), e))
    exceptionTracePrint(self._log)
    self._log.error(errorMsg)
    continue

Since the imp lib is deprecated I want to use importlib. And the only similar method of getting my class instance was to use

pluginModule = importlib.machinery.SourceFileLoader(pluginModuleName, pluginModulePath).load_module()

The weird thing here is that (I am using pyCharm as IDE). when I run my code in debugging mode the above command works fine and I get my class instance. however running the code normally gives me the following error.

pluginModule = importlib.machinery.SourceFileLoader(pluginModuleName, pluginModulePath).load_module()
AttributeError: 'module' object has no attribute 'machinery'

Why is there a difference between run and debug. Is there an alternative way of doing what I want.

Ive also tried

pluginModuleTmp = importlib.util.spec_from_file_location(pluginModuleName, pluginModulePath)

Which also gives me the correct data however I cannot load the module this way or at least I do not know how

Regards Anders


回答1:


Found the solution. Apparently in debug mode a lot more modules are imported behind my back. I fixed it by adding the import.

import importlib.machinery

Regards Anders



来源:https://stackoverflow.com/questions/32987304/problems-when-converting-from-imp-to-importlib-in-python-3-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!