用于创建和导入插件的框架
pluginlib的Python项目详细描述
概述
pluginlib使为项目创建插件变得简单。
功能
- 插件在导入时进行验证
- 插件可以通过不同的机制加载(模块、文件系统路径、entry points)
- 支持同一个插件的多个versions(默认情况下使用最新的插件)
- 插件可以按类型、名称或版本blacklisted
- 支持多个plugin groups,因此一个程序可以使用多组不冲突的插件
- 插件支持conditional loading(例如:操作系统、版本、已安装的软件等)
- 加载后,插件可以通过字典或点符号accessed
安装
PIP
$ pip install pluginlib
EL6和EL7(RHEL/centos/scientific)
(EPEL存储库必须是configured)
$ yum install python-pluginlib $ yum install python34-pluginlib
软呢帽
$ dnf install python2-pluginlib $ dnf install python3-pluginlib
用法
步骤1:定义插件父类
所有插件都是父类的子类。要创建父类,请使用 @Parent装饰工。
装饰器可以采用插件类型来访问子插件 父母的。如果没有给出插件类型,将使用类名。
@Parentdecorator还可以使用一个group关键字 将插件限制到特定的插件组。group如果插件用于 不同的项目可以在一个程序中访问,例如使用库和框架。 有关详细信息,请参见Plugin Groups部分。
子插件中所需的方法应标记为抽象方法。 没有这些方法或参数的插件 不匹配的,将不会加载。 有关详细信息,请参见Abstract Methods部分。
""" sample.py """importpluginlib@pluginlib.Parent('parser')classParser(object):@pluginlib.abstractmethoddefparse(self,string):pass
步骤2:定义插件类
若要创建插件,请子类化父类并包含任何必需的方法。
插件可以通过可选的类属性定制:
- _alias_
- Changes the name of the plugin which defaults to the class name.
- _version_
- Sets the version of the plugin. Defaults to the module ^{tt3}$ or ^{tt4}$ If multiple plugins with the same type and name are loaded, the plugin with the highest version is used. For more information, see the Versions section.
- _skipload_
- Specifies the plugin should not be loaded. This is useful when a plugin is a parent class for additional plugins or when a plugin should only be loaded under certain conditions. For more information see the Conditional Loading section.
""" sample_plugins.py """importjsonimportsampleclassJSON(sample.Parser):_alias_='json'defparse(self,string):returnjson.loads(string)
步骤3:加载插件
插件在导入它们所在的模块时加载。PluginLoader 将从指定位置加载模块并提供对它们的访问。
- PluginLoader可以从多个位置加载插件。
- 程序的标准库
- Entry points
- 模块列表
- 文件系统路径列表
插件也可以通过黑名单和类型过滤器过滤。 有关详细信息,请参见Blacklists和Type Filters部分。
插件可以通过PluginLoader.plugins属性访问, 可通过点符号访问的嵌套字典。对于访问插件的其他方式, 请参阅Accessing Plugins部分。
importpluginlibimportsampleloader=pluginlib.PluginLoader(modules=['sample_plugins'])plugins=loader.pluginsparser=plugins.parser.json()print(parser.parse('{"json": "test"}'))