python插件式实现

2019-11-08

plug.jpg

app.py

import importlib

Plugins = [
    "plugins.email.Email",
    "plugins.msg.Msg"
]

def sends(content):
    for p in Plugins:
        # module: plugins.email, className: Email
        module, className = p.rsplit('.',maxsplit=1)
        print("module: %s, className: %s" % (module,className) )
        # 相当from plugins import email
        mod = importlib.import_module(module)
        # 利用反射获取模块中的类名
        cls = getattr(mod, className)
        obj = cls()
        obj.send(content)

sends("hello world")

plugins包下添加模块
email.py

class Email:
    def send(self,content):
        print("This is plugin email => %s" % content)

msg.py

class Msg:
    def send(self,content):
        print("This is plugin Msg => %s" % content)

标题:python插件式实现
作者:fish2018
地址:http://www.devopser.org/articles/2019/11/08/1573179335967.html

评论
发表评论