python实现事件驱动


Posted in Python onNovember 21, 2018

本文实例为大家分享了python实现事件驱动的具体代码,供大家参考,具体内容如下

EventManager事件管理类实现,大概就百来行代码左右。

# encoding: UTF-8
# 系统模块
from Queue import Queue, Empty
from threading import *
#################################################
class EventManager:
 #----------------------------------------------------------------------
 def __init__(self):
  """初始化事件管理器"""
  # 事件对象列表
  self.__eventQueue = Queue()
  # 事件管理器开关
  self.__active = False
  # 事件处理线程
  self.__thread = Thread(target = self.__Run)
 
  # 这里的__handlers是一个字典,用来保存对应的事件的响应函数
  # 其中每个键对应的值是一个列表,列表中保存了对该事件监听的响应函数,一对多
  self.__handlers = {}
 
 #----------------------------------------------------------------------
 def __Run(self):
  """引擎运行"""
  while self.__active == True:
   try:
    # 获取事件的阻塞时间设为1秒
    event = self.__eventQueue.get(block = True, timeout = 1) 
    self.__EventProcess(event)
   except Empty:
    pass
 
 #----------------------------------------------------------------------
 def __EventProcess(self, event):
  """处理事件"""
  # 检查是否存在对该事件进行监听的处理函数
  if event.type_ in self.__handlers:
   # 若存在,则按顺序将事件传递给处理函数执行
   for handler in self.__handlers[event.type_]:
    handler(event)
 
 #----------------------------------------------------------------------
 def Start(self):
  """启动"""
  # 将事件管理器设为启动
  self.__active = True
  # 启动事件处理线程
  self.__thread.start()
 
 #----------------------------------------------------------------------
 def Stop(self):
  """停止"""
  # 将事件管理器设为停止
  self.__active = False
  # 等待事件处理线程退出
  self.__thread.join()
 
 #----------------------------------------------------------------------
 def AddEventListener(self, type_, handler):
  """绑定事件和监听器处理函数"""
  # 尝试获取该事件类型对应的处理函数列表,若无则创建
  try:
   handlerList = self.__handlers[type_]
  except KeyError:
   handlerList = []
 
  self.__handlers[type_] = handlerList
  # 若要注册的处理器不在该事件的处理器列表中,则注册该事件
  if handler not in handlerList:
   handlerList.append(handler)
 
 #----------------------------------------------------------------------
 def RemoveEventListener(self, type_, handler):
  """移除监听器的处理函数"""
  #读者自己试着实现
 
 #----------------------------------------------------------------------
 def SendEvent(self, event):
  """发送事件,向事件队列中存入事件"""
  self.__eventQueue.put(event)
 
########################################################################
"""事件对象"""
class Event:
 def __init__(self, type_=None):
  self.type_ = type_  # 事件类型
  self.dict = {}   # 字典用于保存具体的事件数据

测试代码

#-------------------------------------------------------------------
# encoding: UTF-8
import sys
from datetime import datetime
from threading import *
from EventManager import *
 
#事件名称 新文章
EVENT_ARTICAL = "Event_Artical"
 
#事件源 公众号
class PublicAccounts:
 def __init__(self,eventManager):
  self.__eventManager = eventManager
 def WriteNewArtical(self):
  #事件对象,写了新文章
  event = Event(type_=EVENT_ARTICAL)
  event.dict["artical"] = u'如何写出更优雅的代码\n'
  #发送事件
  self.__eventManager.SendEvent(event)
  print u'公众号发送新文章\n'
 
#监听器 订阅者
class Listener:
 def __init__(self,username):
  self.__username = username
 
 #监听器的处理函数 读文章
 def ReadArtical(self,event):
  print(u'%s 收到新文章' % self.__username)
  print(u'正在阅读新文章内容:%s' % event.dict["artical"])
 
"""测试函数"""
#--------------------------------------------------------------------
def test():
 listner1 = Listener("thinkroom") #订阅者1
 listner2 = Listener("steve")#订阅者2
 
 eventManager = EventManager()
 
 #绑定事件和监听器响应函数(新文章)
 eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical)
 eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical)
 eventManager.Start()
 
 publicAcc = PublicAccounts(eventManager)
 timer = Timer(2, publicAcc.WriteNewArtical)
 timer.start()
 
if __name__ == '__main__':
 test()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
基于Linux系统中python matplotlib画图的中文显示问题的解决方法
Jun 15 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
Jun 23 Python
python 中的list和array的不同之处及转换问题
Mar 13 Python
python中plot实现即时数据动态显示方法
Jun 22 Python
python构建基础的爬虫教学
Dec 23 Python
Python判断对象是否为文件对象(file object)的三种方法示例
Apr 26 Python
Python进度条的制作代码实例
Aug 31 Python
python实现简易淘宝购物
Nov 22 Python
python使用beautifulsoup4爬取酷狗音乐代码实例
Dec 04 Python
python基于TCP实现的文件下载器功能案例
Dec 10 Python
keras使用Sequence类调用大规模数据集进行训练的实现
Jun 22 Python
Python Opencv图像处理基本操作代码详解
Aug 31 Python
python事件驱动event实现详解
Nov 21 #Python
python程序封装为win32服务的方法
Mar 07 #Python
pygame游戏之旅 添加icon和bgm音效的方法
Nov 21 #Python
pygame游戏之旅 添加游戏暂停功能
Nov 21 #Python
使用50行Python代码从零开始实现一个AI平衡小游戏
Nov 21 #Python
pygame游戏之旅 调用按钮实现游戏开始功能
Nov 21 #Python
pygame游戏之旅 按钮上添加文字的方法
Nov 21 #Python
You might like
一组PHP加密解密函数分享
2014/06/05 PHP
php curl 上传文件代码实例
2015/04/27 PHP
PHP实现批量上传单个文件
2015/12/29 PHP
PHP实现获取并生成数据库字典的方法
2016/05/04 PHP
PHP-FPM 的管理和配置详解
2019/02/17 PHP
在ASP.NET中使用JavaScript脚本的方法
2013/11/12 Javascript
javascript实现通过表格绘制颜色填充矩形的方法
2015/04/21 Javascript
js实现仿MSN带关闭功能的右下角弹窗代码
2015/09/04 Javascript
Knockout结合Bootstrap创建动态UI实现产品列表管理
2016/09/14 Javascript
JavaScript制作颜色反转小游戏
2016/09/25 Javascript
Javascript json object 与string 相互转换的简单实现
2016/09/27 Javascript
jquery获取select,option所有的value和text的实例
2017/03/06 Javascript
vue+VeeValidate 校验范围实例详解(部分校验,全部校验)
2018/10/19 Javascript
webpack4手动搭建Vue开发环境实现todoList项目的方法
2019/05/16 Javascript
在 Vue 应用中使用 Netlify 表单功能的方法详解
2019/06/03 Javascript
JS常见错误(Error)及处理方案详解
2020/07/02 Javascript
[01:35]2018年度CS GO最佳战队-完美盛典
2018/12/17 DOTA
[05:37]DOTA2-DPC中国联赛 正赛 Elephant vs iG 选手采访
2021/03/11 DOTA
python发送邮件示例(支持中文邮件标题)
2014/02/16 Python
自动化Nginx服务器的反向代理的配置方法
2015/06/28 Python
Python字符串格式化输出方法分析
2016/04/13 Python
Python如何使用paramiko模块连接linux
2020/03/18 Python
python对指定字符串逆序的6种方法(小结)
2020/04/02 Python
Python中的全局变量如何理解
2020/06/04 Python
使用pytorch实现论文中的unet网络
2020/06/24 Python
C语言笔试题回忆
2015/04/02 面试题
北京麒麟网信息技术有限公司网络游戏测试面试题
2013/09/28 面试题
面料业务员岗位职责
2013/12/26 职场文书
项目副经理岗位职责
2013/12/30 职场文书
数控专业大学毕业生职业规划范文
2014/02/06 职场文书
市场营销管理毕业生自荐信
2014/03/03 职场文书
综合办公室主任岗位职责
2014/04/13 职场文书
电焊工岗位工作职责
2014/07/09 职场文书
生产现场禁烟通知
2015/04/23 职场文书
2015年乡镇妇联工作总结
2015/05/19 职场文书
2015年妇幼卫生工作总结
2015/05/23 职场文书