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 signal was caught
43 # Alarm Signal handler
44 def signal_handler(signum, stack_frame):
46 signals.append(signum)
49 r"""EventLoop(file[, handler[, signals]]]) -> 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 'signals' is a dictionary with signals to be handled by the loop,
58 where keys are signal numbers and values are callbacks (which takes
59 2 arguments, first the event loop that captured the signal, and then
60 the captured signal number). Callbacks can be None if all signals
61 are handled by the handle_signal() member function.
63 This is a really simple example of usage using a hanlder callable:
66 >>> def handle(event_loop):
67 data = os.read(event_loop.fileno, 100)
68 os.write(1, 'Received message: %r\n' % data)
69 >>> p = EventLoop(0, handle)
72 In this example only one event is handled (see the 'once' argument
75 A more complex example, making a subclass and explicitly stopping
76 the loop, looks something like this:
78 >>> class Test(EventLoop):
80 >>> data = os.read(self.fileno, 100)
81 >>> os.write(1, 'Received message: %r\n' % data)
82 >>> def handle_signal(self, signum):
83 >>> os.write(1, 'Signal %d received, stopping\n' % signum)
85 >>> p = Test(0, signals={signal.SIGTERM: None, signal.SIGINT: None})
88 This example loops until the user enter interrupts the program (by
89 pressing Ctrl-C) or untile the program is terminated by a TERM signal
90 (kill) when stop() is called and the event loop is exited.
93 def __init__(self, file, handler=None, signals=None):
94 r"""Initialize the EventLoop object.
96 See EventLoop class documentation for more info.
98 self.poll = select.poll()
100 self.__register(file)
101 self.handler = handler
102 self.signals = dict()
105 for (signum, sighandler) in signals.items():
106 self.set_signal(signum, sighandler)
108 def __register(self, file):
109 r"__register(file) -> None :: Register a new file for polling."
111 self.poll.register(self.fileno, POLLIN | POLLPRI | POLLERR)
113 def set_signal(self, signum, sighandler):
114 prev = self.signals.get(signum, None)
115 # If the signal was not already handled, handle it
116 if signum not in self.signals:
117 signal.signal(signum, signal_handler)
118 self.signals[signum] = sighandler
121 def get_signal_handler(self, signum):
122 return self.signals[signum]
124 def unset_signal(self, signum):
125 prev = self.signals[signum]
126 # Restore the default handler
127 signal.signal(signum, signal.SIG_DFL)
130 def set_file(self, file):
131 r"""set_file(file) -> None :: New file object to be monitored
133 Unregister the previous file object being monitored and register
136 self.poll.unregister(self.fileno)
137 self.__register(file)
140 r"get_file() -> file object/int :: Get the current file object/fd."
143 file = property(get_file, set_file, doc='File object (or descriptor)')
145 def get_fileno(self):
146 r"get_fileno() -> int :: Get the current file descriptor"
147 if hasattr(self.file, 'fileno'):
148 return self.file.fileno()
151 fileno = property(get_fileno, doc='File descriptor (never a file object)')
154 r"""stop() -> None :: Stop the event loop.
156 The event loop will be interrupted as soon as the current handler
161 def loop(self, once=False):
162 r"""loop([once]) -> None :: Wait for events.
164 Wait for events and handle then when they arrive. If once is True,
165 then only 1 event is processed and then this method returns.
167 # List of pending signals
171 res = self.poll.poll()
172 except select.error, e:
173 # The error is not an interrupt caused by a signal, then raise
174 if e.args[0] != errno.EINTR or not signals:
175 raise LoopInterruptedError(e)
176 # If we have signals to process, we just do it
177 have_signals = bool(signals)
179 self.handle_signal(signals.pop(0))
180 # No signals to process, execute the regular handler
184 # Look if we have to stop
185 if self._stop or once:
190 r"handle() -> None :: Handle file descriptor events."
193 def handle_signal(self, signum):
194 r"handle_signal(signum) -> None :: Handles signals."
195 self.signals[signum](self, signum)
197 if __name__ == '__main__':
202 def handle(event_loop):
203 data = os.read(event_loop.fileno, 100)
204 os.write(1, 'Received message: %r\n' % data)
206 p = EventLoop(0, handle)
208 os.write(1, 'Say something once: ')
210 os.write(1, 'Great!\n')
212 class Test(EventLoop):
214 data = os.read(self.fileno, 100)
215 os.write(1, 'Received message: %r\n' % data)
216 def handle_signal(self, signum):
217 os.write(1, 'Signal %d received, stopping\n' % signum)
220 p = Test(0, signals={signal.SIGTERM: None, signal.SIGINT: None})
222 os.write(1, 'Say a lot of things, then press Ctrl-C or kill me to stop: ')
224 os.write(1, 'Ok, bye!\n')