Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Event Loop in Python [duplicate]

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?

like image 304
Matt Seymour Avatar asked Oct 25 '12 08:10

Matt Seymour


1 Answers

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.

like image 138
glglgl Avatar answered Sep 28 '22 17:09

glglgl