如何调用已加载的插件模块?

时间:2012-08-08 08:45:00

标签: python plugins dynamic module loading

要么睡眠不足,但我觉得愚蠢,我无法得到这个。我有一个插件,我看到它已加载但我无法在我的主文件中实例化它:

from transformers.FOMIBaseClass import find_plugins, register
find_plugins()

这是我的FOMIBaseClass:

from PluginBase import MountPoint
import sys
import os

class FOMIBaseClass(object):
    __metaclass__ = MountPoint

    def __init__(self):
        pass

    def init_plugins(self):
        pass

def find_plugins():
    plugin_dir = os.path.dirname(os.path.realpath(__file__))
    plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith("Transformer.py")]
    sys.path.insert(0, plugin_dir)
    for plugin in plugin_files:
        mod = __import__(plugin)

这是我的MountPoint:

class MountPoint(type):
    def __init__(cls,name,bases,attrs):
        if not hasattr(cls,'plugins'):
            cls.plugins = []
        else:
            cls.plugins.append(cls)

我看到它正在加载:

# /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.pyc matches /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.py
import SctyDistTransformer # precompiled from /Users/carlos/Desktop/ws_working_folder/python/transformers/SctyDistTransformer.pyc

但是,对于我的生活,我无法从主文件中实例化'SctyDistTransformer'模块。我知道我错过了一些微不足道的东西。基本上,我想使用类加载插件。

1 个答案:

答案 0 :(得分:0)

要从任意文件夹中加载Python模块,请使用imp模块:

http://docs.python.org/library/imp.html

具体来说,代码应如下所示:

   mod = imp.load_source("MyModule", "MyModule.py")
   clz = getattr(mod, "MyClassName")

此外,如果您正在构建严格的插件架构,我建议使用Python egg和入口点:

http://wiki.pylonshq.com/display/pylonscookbook/Using+Entry+Points+to+Write+Plugins

https://github.com/miohtama/vvv/blob/master/vvv/main.py#L104