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 相关文章推荐
Python下的常用下载安装工具pip的安装方法
Nov 13 Python
python套接字流重定向实例汇总
Mar 03 Python
python随机取list中的元素方法
Apr 08 Python
Python Flask框架扩展操作示例
May 03 Python
对python3 Serial 串口助手的接收读取数据方法详解
Jun 12 Python
pycharm显示远程图片的实现
Nov 04 Python
python 的topk算法实例
Apr 02 Python
python中shell执行知识点
May 06 Python
浅析python函数式编程
Sep 26 Python
python批量修改文件名的示例
Sep 27 Python
Pandas替换及部分替换(replace)实现流程详解
Oct 12 Python
Python实现Hash算法
Mar 18 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
动漫定律:眯眯眼都是怪物!这些角色狠话不多~
2020/03/03 日漫
PHP页面实现定时跳转的方法
2014/10/31 PHP
微信公众号开发之微信公共平台消息回复类实例
2014/11/14 PHP
PHP多进程之pcntl_fork的实例详解
2017/10/15 PHP
浅谈laravel中的关联查询with的问题
2019/10/10 PHP
PHP的重载使用魔术方法代码实例详解
2021/02/26 PHP
jQuery 顺便学习下CSS选择器 奇偶匹配nth-child(even)
2010/05/24 Javascript
Prototype源码浅析 String部分(四)之补充
2012/01/16 Javascript
JS实现密码框根据焦点的获取与失去控制文字的消失与显示效果
2015/11/26 Javascript
解析Node.js基于模块和包的代码部署方式
2016/02/16 Javascript
Javascript的比较汇总
2016/07/25 Javascript
nodejs入门教程三:调用内部和外部方法示例
2017/04/24 NodeJs
js图片上传的封装代码
2017/08/01 Javascript
JavaScript根据json生成html表格的示例代码
2018/10/24 Javascript
在Web关闭页面时发送Ajax请求的实现方法
2019/03/07 Javascript
Moment.js实现多个同时倒计时
2019/08/26 Javascript
如何在vue中使用kindeditor富文本编辑器
2020/12/19 Vue.js
[01:02:17]2014 DOTA2华西杯精英邀请赛 5 24 DK VS VG
2014/05/26 DOTA
Python列表append和+的区别浅析
2015/02/02 Python
基于Python中numpy数组的合并实例讲解
2018/04/04 Python
Python魔法方法详解
2019/02/13 Python
python celery分布式任务队列的使用详解
2019/07/08 Python
详解Python对JSON中的特殊类型进行Encoder
2019/07/15 Python
python中多个装饰器的调用顺序详解
2019/07/16 Python
解决安装pyqt5之后无法打开spyder的问题
2019/12/13 Python
python中plt.imshow与cv2.imshow显示颜色问题
2020/07/16 Python
Kappa英国官方在线商店:服装和运动器材
2020/11/22 全球购物
Shell脚本如何向终端输出信息
2014/04/25 面试题
儿科主治医生个人求职信
2013/09/23 职场文书
函授本科自我鉴定
2014/02/04 职场文书
《鸟的天堂》教学反思
2014/02/27 职场文书
员工趣味活动方案
2014/08/27 职场文书
审计局2014法制宣传日活动总结
2014/11/01 职场文书
幼儿园六一儿童节主持词
2015/06/30 职场文书
使用Mysql计算地址的经纬度距离和实时位置信息
2022/04/29 MySQL
MySQL数据库配置信息查看与修改方法详解
2022/06/25 MySQL