1 # vim: set encoding=utf-8 et sw=4 sts=4 :
6 Please see EventLoop class documentation for more info.
12 from select import POLLIN, POLLPRI, POLLERR
14 __ALL__ = ('EventLoop', 'LoopInterruptedError')
16 class LoopInterruptedError(RuntimeError):
18 LoopInterruptedError(select_error) -> LoopInterruptedError instance.
20 This class is raised when the event loop is interrupted in an unexpected
21 way. It wraps a select error, which can be accessed using the 'select_error'
25 def __init__(self, select_error):
26 r"""Initialize the object.
28 See the class documentation for more info.
30 self.select_error = select_error
33 r"repr(obj) -> Object representation."
34 return 'LoopInterruptedError(select_error=%r)' % self.select_error
37 r"str(obj) -> String representation."
38 return 'Loop interrupted: %s' % self.select_error
40 # Flag to know if a timer was expired
43 # Alarm Signal handler
44 def alarm_handler(signum, stack_frame):
49 r"""EventLoop(file[, timer[, handler[, timer_handler]]]) -> EventLoop.
51 This class implements a simple event loop based on select module.
52 It "listens" to activity a single 'file' object (a file, a pipe,
53 a socket, or even a simple file descriptor) and calls a 'handler'
54 function (or the handle() method if you prefer subclassing) every
55 time the file is ready for reading (or has an error).
57 If a 'timer' is supplied, then the timer_handler() function object
58 (or the handle_timer() method) is called every 'timer' seconds.
60 This is a really simple example of usage using a hanlder callable:
63 >>> def handle(event_loop):
64 data = os.read(event_loop.fileno, 100)
65 os.write(1, 'Received message: %r\n' % data)
66 >>> p = EventLoop(0, handle)
69 In this example only one event is handled (see the 'once' argument
72 A more complex example, making a subclass and explicitly stopping
73 the loop, looks something like this:
75 >>> class Test(EventLoop):
77 >>> data = os.read(self.fileno, 100)
81 >>> os.write(1, 'Received message: %r\n' % data)
82 >>> def handle_timer(self):
83 >>> print time.strftime('%c')
84 >>> p = Test(0, timer=5)
87 This example loops until the user enters a single "q", when stop()
88 is called and the event loop is exited.
91 def __init__(self, file, handler=None, timer=None, timer_handler=None):
92 r"""Initialize the EventLoop object.
94 See EventLoop class documentation for more info.
96 self.poll = select.poll()
100 self.handler = handler
101 self.timer_handler = timer_handler
103 def __register(self, file):
104 r"__register(file) -> None :: Register a new file for polling."
106 self.poll.register(self.fileno, POLLIN | POLLPRI | POLLERR)
108 def set_file(self, file):
109 r"""set_file(file) -> None :: New file object to be monitored
111 Unregister the previous file object being monitored and register
114 self.poll.unregister(self.fileno)
115 self.__register(file)
118 r"get_file() -> file object/int :: Get the current file object/fd."
121 file = property(get_file, set_file, doc='File object (or descriptor)')
123 def get_fileno(self):
124 r"get_fileno() -> int :: Get the current file descriptor"
125 if hasattr(self.file, 'fileno'):
126 return self.file.fileno()
129 fileno = property(get_fileno, doc='File descriptor (never a file object)')
132 r"""stop() -> None :: Stop the event loop.
134 The event loop will be interrupted as soon as the current handler
139 def loop(self, once=False):
140 r"""loop([once]) -> None :: Wait for events.
142 Wait for events and handle then when they arrive. If once is True,
143 then only 1 event is processed and then this method returns.
145 # Flag modified by the signal handler
147 # If we use a timer, we set up the signal
148 if self.timer is not None:
149 signal.signal(signal.SIGALRM, alarm_handler)
151 signal.alarm(self.timer)
154 res = self.poll.poll()
155 except select.error, e:
156 # The error is not an interrupt caused by the alarm, then raise
157 if e.args[0] != errno.EINTR or not timeout:
158 raise LoopInterruptedError(e)
159 # There was a timeout, so execute the timer handler
163 signal.alarm(self.timer)
164 # Not a timeout, execute the regular handler
167 # Look if we have to stop
168 if self._stop or once:
173 r"handle() -> None :: Abstract method to be overriden to handle events."
176 def handle_timer(self):
177 r"handle() -> None :: Abstract method to be overriden to handle events."
178 self.timer_handler(self)
180 if __name__ == '__main__':
185 def handle(event_loop):
186 data = os.read(event_loop.fileno, 100)
187 os.write(1, 'Received message: %r\n' % data)
189 p = EventLoop(0, handle)
191 os.write(1, 'Say something once: ')
193 os.write(1, 'Great!\n')
195 class Test(EventLoop):
197 data = os.read(self.fileno, 100)
201 os.write(1, 'Received message: %r\n' % data)
202 def handle_timer(self):
203 print time.strftime('%c')
207 os.write(1, 'Say a lot of things, then press write just "q" to stop: ')
209 os.write(1, 'Ok, bye!\n')