扫描目录以从c++加载Python插件
Scan a directory to load Python plugin from C++
我想做一个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库,以便你将来可以维护它。
相关文章:
- 如何在C++中使用pybind11加载一个pickle python列表
- Python ctypes:不会按预期加载 dll
- 如何将经过训练的机器学习模型保存在python中并将其加载到C++中进行预测?
- 无法使用 python ctypes 加载C++共享库
- 如何在python中加载C # / C++ dll?
- 保存在(Python)tensorflow中的权重未加载到C++tf中
- 尝试在 python 中正确加载和使用 dll 文件
- 将数据保存在C++中,从 Python 加载 - 推荐的数据格式
- 使用 Python "cPickle.load"加载C++编写的二进制文件时的 EOFError
- 无法在 Python 3.5 上导入 cv2 DLL 加载失败
- 在共享C++库中加载共享库时C++未定义的符号,该库本身由 Python 加载
- 在Python中加载共享库时未定义的符号
- 可以加载C/C++和Python插件的应用程序
- 无法在Python中加载C DLL
- 在Python脚本中加载.SO文件时未定义的符号错误
- Python C API-重新加载模块
- 如何在 Python 中从 SXS 加载 C DLL
- 使用 Boost.Python 从 DLL 动态加载 python 模块
- 扫描目录以从c++加载Python插件
- 在3.3中加载python模块时,我使用什么代替PyString_AsString ?