I'm trying to make a simple urwid an output screen for an endless loop. It needs to output data coming from another class.
The solution I've found right now is: have a Printer class (a test replacer for the actual outputting class) with a queue attribute. When it needs to display something, it appends it to queue. Then, there is an Interface class - the actual interface - with its own Printer instance. A thread running in parallel with MainLoop checks if queue has items and, if so, outputs them. Since Printer's main function is an infinite loop, it has its own thread too - in this test, it simply outputs "Hello" every few seconds.
Here is the code:
import urwid
import threading
import time
class Interface:
palette = [
('body', 'white', 'black'),
('ext', 'white', 'dark blue'),
('ext_hi', 'light cyan', 'dark blue', 'bold'),
]
header_text = [
('ext_hi', 'ESC'), ':quit ',
('ext_hi', 'UP'), ',', ('ext_hi', 'DOWN'), ':scroll',
]
def __init__(self):
self.header = urwid.AttrWrap(urwid.Text(self.header_text), 'ext')
self.flowWalker = urwid.SimpleListWalker([])
self.body = urwid.ListBox(self.flowWalker)
self.footer = urwid.AttrWrap(urwid.Edit("Edit: "), 'ext')
self.view = urwid.Frame(
urwid.AttrWrap(self.body, 'body'),
header = self.header,
footer = self.footer)
self.loop = urwid.MainLoop(self.view, self.palette,
unhandled_input = self.unhandled_input)
self.printer = Printer()
def start(self):
t1 = threading.Thread(target = self.fill_screen)
t1.daemon = True
t2 = threading.Thread(target = self.printer.fill_queue)
t2.daemon = True
t1.start()
t2.start()
self.loop.run()
def unhandled_input(self, k):
if k == 'esc':
raise urwid.ExitMainLoop()
def fill_screen(self):
while True:
if self.printer.queue:
self.flowWalker.append(urwid.Text(('body', self.printer.queue.pop(0))))
try:
self.loop.draw_screen()
self.body.set_focus(len(self.flowWalker)-1, 'above')
except AssertionError: pass
def to_screen(self, text):
self.queue.append(text)
class Printer:
def __init__(self):
self.message = 'Hello'
self.queue = []
def fill_queue(self):
while 1:
self.queue.append(self.message)
time.sleep(2)
if __name__ == '__main__':
i = Interface()
i.start()
It works, but it seems way too messy to me and I'm afraid it could end up being some sort of coding horror. Is there a simpler way to accomplish the task?