python 模拟事件触发机制,python事件触发机制,EventManag
python 模拟事件触发机制,python事件触发机制,EventManag
EventManager.py
1 # -*- encoding: UTF-8 -*- 2 3 # 系统模块 4 from queue import Queue, Empty 5 from threading import * 6 7 8 class EventManager: 9 def __init__(self):10 """初始化事件管理器"""11 # 事件对象列表12 self.__eventQueue = Queue()13 # 事件管理器开关14 self.__active = False15 # 事件处理线程16 self.__thread = Thread(target = self.__Run)17 18 # 这里的__handlers是一个字典,用来保存对应的事件的响应函数19 # 其中每个键对应的值是一个列表,列表中保存了对该事件监听的响应函数,一对多20 self.__handlers = {} # {事件类型:[处理事件的方法]}21 22 def __Run(self):23 """引擎运行"""24 while self.__active == True:25 try:26 # 获取事件的阻塞时间设为1秒27 event = self.__eventQueue.get(block = True, timeout = 1) 28 self.__EventProcess(event)29 except Empty:30 pass31 32 def __EventProcess(self, event):33 """处理事件"""34 # 检查是否存在对该事件进行监听的处理函数35 if event.type_ in self.__handlers:36 # 若存在,则按顺序将事件传递给处理函数执行37 for handler in self.__handlers[event.type_]:38 handler(event)39 40 def Start(self):41 """启动"""42 # 将事件管理器设为启动43 self.__active = True44 # 启动事件处理线程45 self.__thread.start()46 47 def Stop(self):48 """停止"""49 # 将事件管理器设为停止50 self.__active = False51 # 等待事件处理线程退出52 self.__thread.join()53 54 def AddEventListener(self, type_, handler):55 """绑定事件和监听器处理函数"""56 # 尝试获取该事件类型对应的处理函数列表,若无则创建57 try:58 handlerList = self.__handlers[type_]59 except KeyError:60 handlerList = []61 62 self.__handlers[type_] = handlerList63 # 若要注册的处理器不在该事件的处理器列表中,则注册该事件64 if handler not in handlerList:65 handlerList.append(handler)66 67 def RemoveEventListener(self, type_, handler):68 """移除监听器的处理函数"""69 #读者自己试着实现70 71 def SendEvent(self, event):72 """发送事件,向事件队列中存入事件"""73 self.__eventQueue.put(event)74 75 """事件对象"""76 class Event:77 def __init__(self, type_=None):78 self.type_ = type_ # 事件类型79 self.dict = {} # 字典用于保存具体的事件数据
test.py
1 # -*- encoding: UTF-8 -*- 2 3 from threading import * 4 from EventManager import * 5 import time 6 7 #事件名称 新文章 8 EVENT_ARTICAL = "Event_Artical" 9 10 11 #事件源 公众号12 class PublicAccounts:13 def __init__(self,eventManager):14 self.__eventManager = eventManager15 16 def WriteNewArtical(self):17 #事件对象,写了新文章18 event = Event(type_=EVENT_ARTICAL)19 event.dict["artical"] = u‘如何写出更优雅的代码\n‘20 #发送事件21 self.__eventManager.SendEvent(event)22 print(u‘公众号发送新文章‘)23 24 25 #监听器 订阅者26 class Listener:27 def __init__(self,username):28 self.__username = username29 30 #监听器的处理函数 读文章31 def ReadArtical(self,event):32 print(u‘%s 收到新文章‘ % self.__username)33 print(u‘正在阅读新文章内容:%s‘ % event.dict["artical"])34 35 36 """测试函数"""37 def test():38 listner1 = Listener("thinkroom") #订阅者139 listner2 = Listener("steve")#订阅者240 41 eventManager = EventManager()42 43 #绑定事件和监听器响应函数(新文章)44 eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical)45 eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical)46 eventManager.Start()47 48 publicAcc = PublicAccounts(eventManager)49 while True:50 publicAcc.WriteNewArtical()51 time.sleep(2)52 53 if __name__ == ‘__main__‘:54 test()
python 模拟事件触发机制
相关内容
- 使用牛顿-拉弗森法定义平方根函数(Newton-Raphson metho
- 关于 使用python向qq好友发送消息(对爬虫的作用----当程
- Python的一个命名空间冲突,关于from-import机制,pythonf
- Python Appium 滑动、点击等操作,pythonappium,Python App
- python爬虫:multipart/form-data格式的POST实体封装与提交,
- Python读取jsonlines格式文件,python读取jsonlines,Python读取
- python学习之----用虚拟环境保存库文件,python----,如果你
- 随机生成双色球号码和商品管理python程序,双色球pyt
- [OpenCV-Python] OpenCV 中的图像处理 部分 IV (二),,部分
- python3_pickle模块详解,python3_pickle详解,python3 pi
评论关闭