Problems converting from imp to importlib in python 3.4

I created a Python application that can load plugins. These plugins are loaded based on name and path.

I am currently using

pluginModule = imp.load_source(pluginModuleName,  pluginModulePath)

and then get an instance of the class 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 imp lib is deprecated, I want to use importlib. And the only similar method to get my class instance was to use

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

The strange thing is (I use pyCharm as an IDE). when I run my code in debug mode, the above command works fine and I get an instance of the class. however, running the code usually causes 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 to do what I want.

I also tried

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

, , , ,

+4
1

. -, . , .

import importlib.machinery

+2

Source: https://habr.com/ru/post/1610546/


All Articles