在python 3.4中从imp转换为importlib时出现问题 [英] Problems when converting from imp to importlib in python 3.4
问题描述
我已经制作了一个可以加载插件的Python应用程序.这些插件是根据名称和路径加载的.
I've made a Python application which can load plugins. These plugins are loaded based on a name and path.
我当前正在使用
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
由于不建议使用imp lib,所以我想使用importlib.而且,获取类实例的唯一类似方法是使用
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()
这很奇怪(我正在使用pyCharm作为IDE).当我在调试模式下运行代码时,上面的命令可以正常工作,并且可以获取类实例.但是,运行代码通常会给我以下错误.
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.
我也尝试过
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
问候 安德斯
推荐答案
找到了解决方案.显然,在调试模式下,有更多的模块被导入到我的背后.我通过添加导入对其进行了修复.
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
问候 安德斯
这篇关于在python 3.4中从imp转换为importlib时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!