我试图将一个简单的urwid输出为无限循环的输出屏幕。它需要输出来自另一个类的数据。
我现在发现的解决方案是:拥有一个带有队列属性的Printer类(实际输出类的测试替换器)。当需要显示某些内容时,它会将其附加到 queue 。然后,有一个Interface类 - 实际的接口 - 与自己的Printer实例。与MainLoop并行运行的线程检查队列是否包含项目,如果是,则输出它们。由于Printer的主要功能是无限循环,它也有自己的线程 - 在这个测试中,它只是输出" Hello"每隔几秒钟。
以下是代码:
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()
它有效,但对我来说似乎太乱了,我担心它最终会成为某种编码恐怖。有没有更简单的方法来完成任务?
答案 0 :(得分:4)
如果您需要外部线程,请考虑以下代码。它设置一个队列,启动一个"将当前时间发送到队列"线程,然后运行主界面。接口会不时地检查共享队列,然后根据需要自行更新。
当接口退出时,外部代码通知线程礼貌地退出。
import logging, Queue, sys, threading, time
import urwid
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)-4s %(threadName)s %(message)s",
datefmt="%H:%M:%S",
filename='trace.log',
)
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, msg_queue):
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.msg_queue = msg_queue
self.check_messages(self.loop, None)
def unhandled_input(self, k):
if k == 'esc':
raise urwid.ExitMainLoop()
def check_messages(self, loop, *_args):
"""add message to bottom of screen"""
loop.set_alarm_in(
sec=0.5,
callback=self.check_messages,
)
try:
msg = self.msg_queue.get_nowait()
except Queue.Empty:
return
self.flowWalker.append(
urwid.Text(('body', msg))
)
self.body.set_focus(
len(self.flowWalker)-1, 'above'
)
def update_time(stop_event, msg_queue):
"""send timestamp to queue every second"""
logging.info('start')
while not stop_event.wait(timeout=1.0):
msg_queue.put( time.strftime('time %X') )
logging.info('stop')
if __name__ == '__main__':
stop_ev = threading.Event()
message_q = Queue.Queue()
threading.Thread(
target=update_time, args=[stop_ev, message_q],
name='update_time',
).start()
logging.info('start')
Interface(message_q).loop.run()
logging.info('stop')
# after interface exits, signal threads to exit, wait for them
logging.info('stopping threads')
stop_ev.set()
for th in threading.enumerate():
if th != threading.current_thread():
th.join()