Python event trigger mechanism and python trigger mechanism

Source: Internet
Author: User

Python event trigger mechanism and python trigger mechanism

The example in this article shares the code of the python Simulated Event trigger mechanism for your reference. The details are as follows:

EventManager. py

#-*-Encoding: UTF-8-*-# system module from queue import Queue, Emptyfrom threading import * class EventManager: def _ init _ (self ): "initialize event manager" # event object list self. _ eventQueue = Queue () # Switch event manager self. _ active = False # event processing thread self. _ thread = Thread (target = self. _ Run) # Here _ handlers is a dictionary used to save the corresponding Event Response Function # the value of each key is a list, the list stores the response function listening for this event, one-to-multiple self. _ handlers ={}# {event type: [event processing method]} def _ Run (self): "engine running" while self. _ active = True: try: # Set the event blocking time to 1 second event = self. _ eventQueue. get (block = True, timeout = 1) self. _ EventProcess (event) failed t Empty: pass def _ EventProcess (self, event ): "Processing event" # check whether there is a processing function if event that listens to this event. type _ in self. _ handlers: # If an event exists, the event is passed to the processing function in order to execute for handler in self. _ handlers [event. type _]: handler (event) def Start (self): "Start" "# Set event manager to Start self. _ active = True # Start the event processing thread self. _ thread. start () def Stop (self): "Stop" "# Set event manager to Stop self. _ active = False # Wait for the event processing thread to exit self. _ thread. join () def AddEventListener (self, type _, handler): "binding events and listener handler functions" "# try to obtain the handler list corresponding to this event type, if none, create try: handlerList = self. _ handlers [type _] handle T KeyError: handlerList = [] self. _ handlers [type _] = handlerList # if the processor to be registered is not in the processor list of the event, register the event if handler not in handlerList: handlerList. append (handler) def RemoveEventListener (self, type _, handler): "Remove listener handler" # The Reader tries to implement def SendEvent (self, event ): "Send events and store events in the event queue" self. _ eventQueue. put (event) "Event object" class event: def _ init _ (self, type _ = None): self. type _ = type _ # Event type self. dict = {}# the dictionary is used to save specific event data.

Test. py

#-*-Encoding: UTF-8-*-from threading import * from EventManager import * import time # event name new article EVENT_ARTICAL = "Event_Artical" # event source public account class PublicAccounts: def _ init _ (self, eventManager): self. _ eventManager = eventManager def WriteNewArtical (self): # event object, new article Event = event (type _ = EVENT_ARTICAL) event. dict ["artical"] = u'how to write more elegant code \ n' # Send event self. _ eventManager. sendEvent (event) print (u'send new article with public number') # Listener subscriber class Listener: def _ init _ (self, username): self. _ username = username # handler of the listener read the article def ReadArtical (self, event): print (u '% s received the new article' % self. _ username) print (U' reading new article content: % s' % event. dict ["artical"]) "test function" def test (): listner1 = Listener ("thinkroom") # subscriber 1 listner2 = Listener ("steve ") # subscriber 2 eventManager = EventManager () # bind event and listener response functions (new article) 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 ()

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.