这个问题有点加载/不清楚,但我会试一试。
我的问题是我不知道如何“解析”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 库,以便将来维护它。