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常用随机数与随机字符串方法实例
Apr 09 Python
基于python的Tkinter实现一个简易计算器
Dec 31 Python
Python获取linux主机ip的简单实现方法
Apr 18 Python
简单讲解Python编程中namedtuple类的用法
Jun 21 Python
Python进阶-函数默认参数(详解)
May 18 Python
python 简单备份文件脚本v1.0的实例
Nov 06 Python
Python3多线程爬虫实例讲解代码
Jan 05 Python
Python unittest 简单实现参数化的方法
Nov 30 Python
python 与服务器的共享文件夹交互方法
Dec 27 Python
在Python中如何传递任意数量的实参的示例代码
Mar 21 Python
使用python模拟高斯分布例子
Dec 09 Python
Django数据库操作之save与update的使用
Apr 01 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编程中八种常见的文件操作方式
2006/11/19 PHP
PHP 实例化类的一点摘记
2008/03/23 PHP
php 信息采集程序代码
2009/03/17 PHP
php面向对象全攻略 (九)访问类型
2009/09/30 PHP
Laravel 4.2 中队列服务(queue)使用感受
2014/10/30 PHP
PHP中抽象类、接口的区别与选择分析
2016/03/29 PHP
php strftime函数获取日期时间(switch用法)
2018/05/16 PHP
很酷的javascript loading效果代码
2008/06/18 Javascript
用JS剩余字数计算的代码
2008/07/03 Javascript
jQuery 对象中的类数组操作
2009/04/27 Javascript
jQuery内置的AJAX功能和JSON的使用实例
2014/07/27 Javascript
jQuery使用prepend()方法在元素前添加内容用法实例
2015/03/26 Javascript
Angular.js实现动态加载组件详解
2017/05/28 Javascript
关于使用axios的一些心得技巧分享
2017/07/02 Javascript
详解如何在react中搭建d3力导向图
2018/01/12 Javascript
详细讲解如何创建, 发布自己的 Vue UI 组件库
2019/05/29 Javascript
vue-cli2与vue-cli3在一台电脑共存的实现方法
2019/09/25 Javascript
vue实现登录拦截
2020/06/29 Javascript
[02:08]DOTA2英雄基础教程 马格纳斯
2014/01/17 DOTA
浅析Python中的多条件排序实现
2016/06/07 Python
python 字典(dict)按键和值排序
2016/06/28 Python
matplotlib中legend位置调整解析
2017/12/19 Python
python 判断linux进程,并杀死进程的实现方法
2019/07/01 Python
Python中typing模块与类型注解的使用方法
2019/08/05 Python
Python Gluon参数和模块命名操作教程
2019/12/18 Python
Python文件操作及内置函数flush原理解析
2020/10/13 Python
html标签之Object和EMBED标签详解
2013/07/04 HTML / CSS
HTML5中外部浏览器唤起微信分享功能的代码
2020/09/15 HTML / CSS
Vrbo西班牙:预订您的度假公寓(公寓、乡村房屋…)
2020/04/27 全球购物
大学生就业自荐信
2013/10/26 职场文书
超市后勤自我鉴定
2014/01/17 职场文书
党员干部承诺书
2014/03/25 职场文书
感恩之星事迹材料
2014/05/03 职场文书
个人三严三实对照检查材料
2014/09/25 职场文书
2016新年年会主持词
2015/07/06 职场文书
多属性、多分类MySQL模式设计
2021/04/05 MySQL