Learn about an example of the Python process

Source: Internet
Author: User

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

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: info-contact@alibabacloud.com 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.