python模拟事件触发机制详解


Posted in Python onJanuary 19, 2018

本文实例为大家分享了python模拟事件触发机制的具体代码,供大家参考,具体内容如下

EventManager.py

# -*- 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 = {}     # 字典用于保存具体的事件数据

test.py

# -*- encoding: UTF-8 -*-

from threading import *
from EventManager import *
import time

#事件名称 新文章
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'公众号发送新文章')


#监听器 订阅者
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)
  while True:
    publicAcc.WriteNewArtical()
    time.sleep(2)

if __name__ == '__main__':
  test()

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

Python 相关文章推荐
python time模块用法实例详解
Sep 11 Python
Python聊天室程序(基础版)
Apr 01 Python
对Python中range()函数和list的比较
Apr 19 Python
Selenium 模拟浏览器动态加载页面的实现方法
May 16 Python
Tensorflow 查看变量的值方法
Jun 14 Python
Django框架之登录后自定义跳转页面的实现方法
Jul 18 Python
python Django的web开发实例(入门)
Jul 31 Python
详解如何用TensorFlow训练和识别/分类自定义图片
Aug 05 Python
利用Vscode进行Python开发环境配置的步骤
Jun 22 Python
解析Tensorflow之MNIST的使用
Jun 30 Python
python使用列表的最佳方案
Aug 12 Python
详解Python flask的前后端交互
Mar 31 Python
flask使用session保存登录状态及拦截未登录请求代码
Jan 19 #Python
简单谈谈python中的lambda表达式
Jan 19 #Python
python使用logging模块发送邮件代码示例
Jan 18 #Python
zookeeper python接口实例详解
Jan 18 #Python
Python获取当前函数名称方法实例分享
Jan 18 #Python
Python AES加密实例解析
Jan 18 #Python
快速了解python leveldb
Jan 18 #Python
You might like
php抽奖小程序的实现代码
2013/06/18 PHP
PHP+apc+ajax实现的ajax_upload上传进度条代码
2016/01/25 PHP
php使用Jpgraph创建折线图效果示例
2017/02/15 PHP
doctype后如何获得body.clientHeight的方法
2007/07/11 Javascript
网页中CDATA标记的说明
2010/09/12 Javascript
关于JavaScript的with 语句的使用方法
2011/05/09 Javascript
jQuery News Ticker 基于jQuery的即时新闻行情展示插件
2011/11/05 Javascript
jQuery插件 selectToSelect使用方法
2013/10/02 Javascript
为指定的元素添加遮罩层的示例代码
2014/01/15 Javascript
javascript + jquery实现定时修改文章标题
2014/03/19 Javascript
动态创建script在IE中缓存js文件时导致编码的解决方法
2014/05/04 Javascript
实例讲解JS中数组Array的操作方法
2014/05/09 Javascript
分享一则JavaScript滚动条插件源码
2015/03/03 Javascript
JavaScript中split与join函数的进阶使用技巧
2016/05/03 Javascript
使用Math.max,Math.min获取数组中的最值实例
2017/04/25 Javascript
Vue集成Iframe页面的方法示例
2017/12/12 Javascript
vue2.0模拟锚点的实例
2018/03/14 Javascript
Vue 监听列表item渲染事件方法
2018/09/06 Javascript
Vue CLI2升级至Vue CLI3的方法步骤
2019/05/20 Javascript
微信小程序实现列表的横向滑动方式
2020/07/15 Javascript
Python中os.path用法分析
2015/01/15 Python
Python实现在线程里运行scrapy的方法
2015/04/07 Python
Python计算三角函数之asin()方法的使用
2015/05/15 Python
python字符串中的单双引
2017/02/16 Python
python让列表倒序输出的实例
2018/06/25 Python
python 抓包保存为pcap文件并解析的实例
2019/07/23 Python
Python实现串口通信(pyserial)过程解析
2019/09/25 Python
python 实现多维数组转向量
2019/11/30 Python
python实现批量修改文件名
2020/03/23 Python
乐天旅游台湾网站:Rakuten Travel TW
2017/06/01 全球购物
美国领先的医疗警报服务:Philips Lifeline
2018/03/12 全球购物
英国最大的宝石首饰超市:QP Jewellers
2018/09/23 全球购物
运动会四百米广播稿
2014/01/19 职场文书
百日安全活动总结
2014/05/04 职场文书
个人股份转让协议书范本
2015/01/28 职场文书
2015年幼儿园中班开学寄语
2015/05/27 职场文书