python的通用插件系统
plugnpla的Python项目详细描述
即插即用
即插即用(pnp)是一个受trac(http://trac.edgewall.org)启发的通用插件系统。 内部组件管理。有了pnp,你可以很容易地把任何程序变成一个可插拔的软件。
您只需定义接口并让其他人实现它们。当你的代码运行时 您可以动态检索谁是实现特定接口的类,并调用 具体方法。
一个简单的例子
这样想:你有一个非常简单的程序,只需复制周围的文件。
假设您想通过计算 两份文件(原件和复印件)。您可以执行md5检查 在主代码中,也可以,但是当需要添加另一个检查时 (例如,计算文件的sha-1)必须修改代码 它可以调用两个方法,md5 checker和sha-1 checker。
使用pnp,你只写程序的主要部分,只做拷贝的部分, 以及可以随时实现的hash checker,,无需进行任何修改 到主代码。
pnp大致上是observer模式(http://en.wikipedia.org/wiki/Observer_pattern)的一个实现。
此示例的代码
好吧,说得太多了,现在来点代码。上述示例的伪代码为:
class CopyListener(Interface): def copy_finished(self, original_file, new_file): pass
主要代码是:
PnP.load_plugins("/some/path/with/python/files") # egg files in the future?. copy_file(file1, file2) # Would return all python classes that # implement CopyListerner interface copy_listeners = CopyListener.implementors() # Call each of the listeners telling the copy finished for listener in copy_listeners: listener.copy_finished(file1, file2)
一个这样的观察者的例子是:
from myproject.interfaces import CopyListener class MD5Check(Plugin): implements = [CopyListener,] def copy_finished(self, file1, file2): md5_1 = hash.md5(file1.read()).hexdigest() md5_2 = hash.md5(file2.read()).hexdigest() if md5_1 is not md5_2: # Do something very useful! =)
结论
你喜欢这个项目吗?很好,帮我写吧!放弃回购 给我一些请求!或者直接跟我说,如果你有一些伟大的想法来实施!
谢谢,
道尔顿·巴雷托