Python实现事件驱动模型:EventManager核心代码解析

码头散步
码头散步
发布时间:2026-10-13| 6人浏览过
原创

本文介绍如何使用Python实现轻量级事件驱动架构。通过EventManager类结合Queue和Thread模块,构建事件总线与监听机制。文章提供核心代码示例,展示如何定义事件、注册监听器及处理异步事件流程,帮助开发者理解基于发布-订阅模式的基础实现原理。

本文分享了一个使用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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。