我想制作一个可以同时处理 C++ 和 Python 插件的 C++ 应用程序。对于 C++ 部分,我很好,但我对 Python 插件有疑问。
我想要做的是拥有一个包含我所有 python 插件的目录,应用程序将加载位于该目录中的所有插件(如 Sublime Text 2)。
我的问题是我不知道如何“解析”python 脚本来获取从我的插件接口(interface)继承的每个类的名称以便创建它们。
- 在 boost.python 中有没有办法做到这一点? (我还没有找到相关信息)
- python 有我可以用来做这个的模块变量吗? (我不是这样 适合 python)
- 我需要使用像 antlr 这样的词法分析器吗? (看起来很重……)
- 我是否需要像 C++ 中那样具有“创建”功能? (崇高的文字 2 似乎不需要那个)
最后,您知道处理 Python 插件的 C++ 应用程序吗?我可以在其中检查代码?
谢谢;)
最佳答案
这个问题有点负载/不清楚,但我会试一试。
My problem is that I don't know how to "parse" a python script to get the name of every class that inherits from my plugin interface in order to create them.
这可以通过 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 库,以便将来维护它。
关于c++ - 扫描目录以从 C++ 加载 Python 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16167049/