【问题标题】:How do I call a plugin module that's loaded?如何调用已加载的插件模块?
【发布时间】:2012-08-05 08:19:18
【问题描述】:

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

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”模块。我知道我错过了一些微不足道的东西。基本上,我想使用一个类加载插件。

【问题讨论】:

    标签: python plugins dynamic module loading


    【解决方案1】:

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

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

    具体代码应如下所示:

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

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

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

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

    【讨论】:

    • 出于好奇,是什么让一个比另一个更好?
    • Python 包(鸡蛋)可以单独分发。 Python 具有发现这些鸡蛋的标准机制,第三方插件可以简单地上传到 pypi.python.org 并使用 easy_install / pip 为您的应用程序安装。缺点是必须管理 Python egg 样板文件,而不是简单地折腾 .py 文件。
    • 另外,Python Egg 声明依赖关系,如果您的插件可能使用第三方 Python 库, Egg 是分发插件的唯一明智方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 2012-11-11
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多