您应该能够拥有应用程序在运行时(或以后)扫描的插件目录以导入相关代码。这是一个应该与常规 .py 或 .pyc 代码一起使用的示例,它甚至可以与存储在 zip 文件中的插件一起使用(因此用户可以将 someplugin.zip 放在“插件”目录中并让它神奇地工作):
import re, os, sys
class Plugin(object):
"""
The base class from which all plugins are derived. It is used by the
plugin loading functions to find all the installed plugins.
"""
def __init__(self, foo):
self.foo = foo
# Any useful base plugin methods would go in here.
def get_plugins(plugin_dir):
"""Adds plugins to sys.path and returns them as a list"""
registered_plugins = []
#check to see if a plugins directory exists and add any found plugins
# (even if they're zipped)
if os.path.exists(plugin_dir):
plugins = os.listdir(plugin_dir)
pattern = ".py$"
for plugin in plugins:
plugin_path = os.path.join(plugin_dir, plugin)
if os.path.splitext(plugin)[1] == ".zip":
sys.path.append(plugin_path)
(plugin, ext) = os.path.splitext(plugin) # Get rid of the .zip extension
registered_plugins.append(plugin)
elif plugin != "__init__.py":
if re.search(pattern, plugin):
(shortname, ext) = os.path.splitext(plugin)
registered_plugins.append(shortname)
if os.path.isdir(plugin_path):
plugins = os.listdir(plugin_path)
for plugin in plugins:
if plugin != "__init__.py":
if re.search(pattern, plugin):
(shortname, ext) = os.path.splitext(plugin)
sys.path.append(plugin_path)
registered_plugins.append(shortname)
return registered_plugins
def init_plugin_system(cfg):
"""
Initializes the plugin system by appending all plugins into sys.path and
then using load_plugins() to import them.
cfg - A dictionary with two keys:
plugin_path - path to the plugin directory (e.g. 'plugins')
plugins - List of plugin names to import (e.g. ['foo', 'bar'])
"""
if not cfg['plugin_path'] in sys.path:
sys.path.insert(0, cfg['plugin_path'])
load_plugins(cfg['plugins'])
def load_plugins(plugins):
"""
Imports all plugins given a list.
Note: Assumes they're all in sys.path.
"""
for plugin in plugins:
__import__(plugin, None, None, [''])
if plugin not in Plugin.__subclasses__():
# This takes care of importing zipped plugins:
__import__(plugin, None, None, [plugin])
因此,假设我在名为“plugins”的目录中(位于我的应用程序的基本目录中)有一个名为“foo.py”的插件,它将为我的应用程序添加新功能。内容可能如下所示:
from plugin_stuff import Plugin
class Foo(Plugin):
"""An example plugin."""
self.menu_entry = {'Tools': {'Foo': self.bar}}
def bar(self):
return "foo plugin!"
当我启动我的应用程序时,我可以像这样初始化我的插件:
plugin_dir = "%s/plugins" % os.getcwd()
plugin_list = get_plugins(plugin_dir)
init_plugin_system({'plugin_path': plugin_dir, 'plugins': plugin_list})
plugins = find_plugins()
plugin_menu_entries = []
for plugin in plugins:
print "Enabling plugin: %s" % plugin.__name__
plugin_menu_entries.append(plugin.menu_entry))
add_menu_entries(plugin_menu_entries) # This is an imaginary function
只要插件是 .py 或 .pyc 文件(假设它是针对相关平台进行字节编译),这应该可以工作。它可以是独立文件,也可以是具有init .py的目录内部或具有相同规则的 zip 文件内部。
我怎么知道这行得通?这就是我在PyCI中实现插件的方式。PyCI 是一个 Web 应用程序,但没有理由为什么这种方法不适用于常规的 ol' GUI。对于上面的示例,我选择使用一个虚构的 add_menu_entries() 函数和一个插件对象变量,该变量可用于将插件的方法添加到 GUI 的菜单中。
希望这个答案能帮助您构建自己的插件系统。如果您想准确了解它是如何实现的,我建议您下载 PyCI 源代码并查看 plugins_enabled 目录中的 plugin_utils.py 和示例插件。