扫描目录以从C ++加载Python插件

时间:2013-04-23 10:30:09

标签: c++ python plugins boost

我想创建一个可以同时处理C ++和Python插件的C ++应用程序。对于C ++部分,我很好,但我对Python插件有疑问。

我想要做的是拥有一个包含所有python插件的目录,应用程序将加载位于此目录中的所有插件(如Sublime Text 2)。

我的问题是我不知道如何“解析”一个python脚本来获取从我的插件接口继承的每个类的名称,以便创建它们。

  • boost.python中有没有办法做到这一点? (我还没有找到有关它的信息)
  • python是否有可用于执行此操作的模块变量? (我不是这样 擅长python)
  • 我是否需要使用像antlr这样的词法分析器? (似乎很重......)
  • 我是否需要像C ++一样拥有“创建”功能? (崇高文本 2似乎不需要那个)

最后,你知道处理Python插件的C ++应用程序,我可以检查代码吗?

谢谢;)

1 个答案:

答案 0 :(得分:3)

这个问题有点不清楚,但我会试一试。

  

我的问题是我不知道如何“解析”一个python脚本来获取从我的插件接口继承的每个类的名称,以便创建它们。

这可以通过python脚本轻松完成;也许你可以编写一个并从你的C ++应用程序中调用它。下面是一段代码,它们找到python脚本'* .py',导入它们,并查找子类名为PluginInterface的类...不确定之后你需要做什么,所以我放了一个TODO那里。

def find_plugins(directory):
    for dirname, _, filenames in os.walk(directory): # recursively search 'directory'
        for filename in filenames:
            # Look for files that end in '.py'
            if (filename.endswith(".py")):
                # Assume the filename is a python module, and attempt to find and load it
                ###  need to chop off the ".py" to get the module_name
                module_name = filename[:-3]
                # Attempt to find and load the module
                try:
                    module_info = imp.find_module(module_name, [dirname])
                    module = imp.load_module(module_name, *module_info)
                    # The module loaded successfully, now look through all
                    # the declarations for an item whose name that matches the module name
                    ##  First, define a predicate to filter for classes from the module
                    ##  that subclass PluginInterface
                    predicate = lambda obj: inspect.isclass(obj) and \
                                            obj.__module__ == module_name and \
                                            issubclass(obj, PluginInterface)
                    for _, declaration in inspect.getmembers(module, predicate):
                        # Each 'declaration' is a class defined in the module that inherits
                        # from 'PluginInterface'; you can instantiate an object of that class
                        # and return it, print the name of the class, etc.
                        # TODO:  fill this in
                        pass
                except:
                    # If anything goes wrong loading the module, skip it quietly
                    pass

也许这足以让你开始,虽然它并不是真的完整,你可能想要了解这里使用的所有python库,以便将来可以维护它。