Plugin Example

2018-07-20 14:13

plug/plug.py (Source)

_processors = []

def register_processor(p):
    _processors.append(p)

def unregister_processor(p):
    _processors.remove(p)

def process(o):
    for p in _processors:
        p(o)

plug/p1.py (Source)

from plug import register_processor

def process(o):
    print(o)
register_processor(process)

plug/p2.py (Source)

from plug import register_processor

def process(o):
    if o is None:
        print("Got a NONE!")
    else:
        print(type(o))
register_processor(process)

plug/c1.py (Source)

import p1
import p2
import plug

plug.process("Hello")
plug.process(None)
plug.process(4)

plug/c1.out (Source)

Hello
<type 'str'>
None
Got a NONE!
4
<type 'int'>

plug/c2.py (Source)

import p1
import plug

plug.process("Hello")
plug.process(None)
plug.process(4)

plug/c2.out (Source)

Hello
None
4

plug/c3.py (Source)

import p2
import plug

plug.process("Hello")
plug.process(None)
plug.process(4)

plug/c3.out (Source)

<type 'str'>
Got a NONE!
<type 'int'>

plug/c4.py (Source)

import plug

plugin_list = ['p1', 'p2']

for p in plugin_list:
    __import__(p)

plug.process("Hello")
plug.process(None)
plug.process(4)

plug/c4.out (Source)

Hello
<type 'str'>
None
Got a NONE!
4
<type 'int'>