如何在调用模块的脚本中使用模块中的变量

时间:2014-01-03 15:17:23

标签: python python-3.x python-module

我想为我的剧本制作一个插件系统。

如何加载插件

插件是存储在指定文件夹中的python模块。

我使用以下代码导入模块:

class Igor:

    # ...

    def load_plugins(self):

        for file in os.listdir(self.plugins_folder):

            try:
                __import__(file)
            except Exception as error:
                sys.exit(error)

    # ...

我希望在插件中提供的变量

我有一个名为igor的变量,它是Igor的实例:

if __name__ == "__main__":

    # ...

    igor = Igor()

    # ...

我希望插件开发人员能够做什么

我想简化插件开发,igor拥有简化插件所需的所有方法。

充其量应该是这样的(在__init__.py中):

from plugins.files.files import Files

igor.register_plugin("files", Files())

我该怎么做?

我真的不知道如何在我的主脚本中执行此globals()显示igor但是菜单中的全局变量中没有任何内容(正如模块所预期的那样,它是沙箱我想的)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要更改Igor类的load_plugins方法:

    def load_plugins(self):
        if not os.path.exists(self.plugins_folder):
            os.makedirs(self.plugins_folder)

        plugin_folder_content = os.listdir(self.plugins_folder)

        for content in plugin_folder_content:
            content_path = os.path.join(self.plugins_folder, content)
            if os.path.isdir(content_path):
                plugin_entry_point_path = os.path.join(content_path, "__init__.py")
                if os.path.exists(plugin_entry_point_path):
                    try:
                         with open(plugin_entry_point_path, 'r') as file:
                             sys.path.insert(1, content_path)
                             exec(compile(file.read(), "script", "exec"), {"igor": self, "IgorPlugin": IgorPlugin, 'path': content_path})
                             sys.path.remove(content_path)
                    except Exception as exc:
                         sys.exit(exc)

这会产生另一个问题:因为我们在每个子目录上定义的每个模块上执行 init .py文件,所以无法轻松导入文件,这就是我传递路径变量的原因,要手动导入文件,这是一个假想的 init .py文件的示例,它导入files.py插件:

import os

files_path = os.path.join(path, "files.py")

exec(compile(open(files_path).read(), "script", "exec"), {"igor": igor, "IgorPlugin": IgorPlugin})
相关问题