1

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

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

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

  • boost.python 中有没有办法做到这一点?(我还没有找到有关它的信息)
  • python 是否有我可以用来执行此操作的模块变量?(我对python不太好)
  • 我需要使用像 antlr 这样的词法分析器吗?(好像很重……)
  • 我是否需要像 C++ 中那样具有“创建”功能?(Sublime Text 2 似乎不需要那个)

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

谢谢 ;)

4

1 回答 1

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 库,以便将来维护它。

于 2013-04-23T23:51:30.780 回答