Basic Event Loop in Python [duplicate]

给你一囗甜甜゛ 提交于 2019-12-09 12:54:23

问题


Possible Duplicate:
Event loop implementation for Python 3?

I am trying to implement an event loop in python2.7. I would like to be able to trigger events based on a time event and as a result of another action taking place.

I understand I can make use of select to do something similar to this.

Is this the right way forwards or is there a better way which I am missing?


回答1:


An event loop is a loop which handles / deals with events.

An event is something that occurs in the system where some code parts might be interested in.

At the beginning, all components register for events, and after that, an init event is fired:

I am just providing raw code here:

listeners = [component1, component2, component3]
eventqueue.add(InitEvent())
while True:
    event = eventqueue.pop()
    for listener in listeners:
        listener.handle_event(event)

How an eventqueue is implemented and what the Event() class hierarchy looks like is left as an exercise for the reader. Take care about using threading.(R)Locks etc. for the .pop() method.

Additionally, you could have separate listener lists for each event type. An event could thus be "fired" by just calling it (or its .fire() method) and have a mechanism to identify all its own and parent's listeners in order to inform them about the event.

In any case, the listeners then can decide on their own what to do with and according to the event.



来源:https://stackoverflow.com/questions/13064373/basic-event-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!