Python事件总线
pyeventbus3的Python项目详细描述
pyeventbus3是python3的发布/订阅事件总线。(python2.7的pyeventbus分支)
- 简化了python类之间的通信
- 分离事件发送者和接收者
- 执行良好的线程、greenlet、队列和并发进程
- 避免复杂和易出错的依赖关系和生命周期问题
- 使代码更简单
- 具有高级功能,如传递线程、工作线程和生成不同的进程等
- 很小(3KB存档)
pyeventbus3分3步:
定义事件:
class MessageEvent: # Additional fields and methods if needed def __init__(self): pass
在准备订阅服务器:声明和注释订阅方法,或者指定线程模式:
^{pr2}$注册您的订户。例如,如果要在Python中注册类:
from pyeventbus3.pyeventbus3 import * class MyClass: def __init__(self): pass def register(self, myclass): PyBus.Instance().register(myclass, self.__class__.__name__) # then during initilization myclass = MyClass() myclass.register(myclass)
在活动后:
from pyeventbus3.pyeventbus3 import * class MyClass: def __init__(self): pass def register(self, myclass): PyBus.Instance().register(myclass, self.__class__.__name__) def postingAnEvent(self): PyBus.Instance().post(MessageEvent()) myclass = MyClass() myclass.register(myclass) myclass.postingAnEvent()
在
模式:pyeventbus可以在5种不同的模式下运行订阅方法
过帐:
Runs the method in the same thread as posted. For example, if an event is posted from main thread, the subscribing method also runs in the main thread. If an event is posted in a seperate thread, the subscribing method runs in the same seperate method This is the default mode, if no mode has been provided:: @subscribe(threadMode = Mode.POSTING, onEvent=MessageEvent) def func(self, event): # Do something pass
在平行:
Runs the method in a seperate python thread:: @subscribe(threadMode = Mode.PARALLEL, onEvent=MessageEvent) def func(self, event): # Do something pass
在绿色小菜:
Runs the method in a greenlet using gevent library:: @subscribe(threadMode = Mode.GREENLET, onEvent=MessageEvent) def func(self, event): # Do something pass
在背景:
Adds the subscribing methods to a queue which is executed by workers:: @subscribe(threadMode = Mode.BACKGROUND, onEvent=MessageEvent) def func(self, event): # Do something pass There is 10 workers by default, see exemple to modify this number.
在
同时:
Runs the method in a seperate python process:: @subscribe(threadMode = Mode.CONCURRENT, onEvent=MessageEvent) def func(self, event): # Do something pass
在
将pyeventbus添加到项目中:
pip install pyeventbus3
示例:
git clone https://github.com/FlavienVernier/pyeventbus.git cd pyeventbus virtualenv venv source venv/bin/activate pip install pyeventbus python example.py
基准和绩效:
Refer /pyeventbus/tests/benchmarks.txt for performance benchmarks on CPU, I/O and networks heavy tasks. Run /pyeventbus/tests/test.sh to generate the same benchmarks. Performance comparison between all the modes with Python and Cython
灵感
Inspired by Eventbus from greenrobot: https://github.com/greenrobot/EventBus
- 项目
标签: