Examples from https://blog.tonyseek.com/post/event-manage-with-greenlet/
Added some notes to read:
The number in the note indicates the order of execution, and this simple example uses the Python-generated generator, the key point is that the module that invokes the generator uses next () to start executing the statements in the generator, where the generator executes to yield and the value of yield is returned to the calling module. When the fire_event (' click ') is executed, another next () is implemented, at which point the generator receives a signal and executes from the suspended place until the end. The stopiteration exception occurs when next () in the response function resume () does not receive the value returned by yield. Thus ending the entire program
#!/usr/bin/env python#coding=utf-8from Time Import sleepevent_listeners = {}def fire_event (name): Event_listeners[name ] () def use_event (func):d EF Call (*args, **kwargs):p rint ' use_event ' # # 1generator = func (*args, **kwargs) # 2print ' Come h Ere ' # # 3event_name = Generator.next () # # 4 Open generator, expecting it to return a yield () value print ' No wait here ' # 7def resume (): Try:print ' s Econd time ' # # 10next (generator) # #唤醒了test_work (), expecting to return a yield (), but Test_work has only one yield (), so there is an exception except Stopiteration:print "test_work () doesn ' t has another yield ()" # # 11passevent_listeners[event_name] = Resumeprint ' Register ' # # 8return call@use_eventdef test_work ():p rint ' Wait ' # 5sleep (2) yield ' click ' # 6 Execute this and return ' click ' to Use_event Next (); Test_work () hangs, waits for another next () to wake print ' click. ' if __name__ = = ' __main__ ': Test_work () sleep (3) fire_event (' click ') #9 wake-up Test_work ()
Learn about an example of the Python process