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

Scan a directory to load Python plugin from C++

本文关键字:加载 Python 插件 c++ 扫描      更新时间:2023-10-16

我想做一个c++应用程序,可以处理c++和Python插件。对于c++部分,我很好,但我对Python插件有疑问。

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

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

  • 是否有一种方法来促进。用Python来做吗?(我没有找到关于它的信息)
  • python有模块变量我可以用它来做这个吗?)我不是这样
  • 我需要使用像antlr这样的词法分析器吗?(看起来很重…)
  • 我需要有一个"创建"函数像在c++ ?(崇高的文本2似乎不需要那个)

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

谢谢,)

这个问题有点复杂/不清楚,但我要试一试。

我的问题是,我不知道如何"解析"一个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库,以便你将来可以维护它。