在Python中显示可编辑数据表
我有一个用Python(2.7)写的脚本,它通过串口读取传入的数据,数据的格式如下:
ID: 648 Data: 45 77 33 9C 26 9A 1F 42
ID: 363 Data: 35 74 36 BC 26 9D
...
这个数据流里有大约30个不同的ID,这些ID会定期重复,每个ID后面跟着2到8个数据字节。ID出现的频率在10到120毫秒之间,有些ID会比其他ID更早重复。
总之,我有一个基本的Python脚本,可以把这个数据流读取到两个变量里,分别是(id和data):
import serial
import re
ser = serial.Serial("COM11", 115200)
while 1:
reading = ser.readline()
matchObj = re.match( r'ID:\s([0-9A-F]+)\sData:\s([^\n]+)', reading, re.M|re.I)
if matchObj:
id = matchObj.group(1)
data = matchObj.group(2)
else:
print "No match!!"
我想做的是实时显示这些数据,以数据表的形式呈现,其中新的ID条目会被添加到表中,而重复的ID条目会被更新。这样一来,表格最开始会随着ID的发现而增长,然后在ID的数据变化时进行更新。
我见过一些表格模块的例子,它们可以让你往表格里添加行,但我还需要能够修改已经存在的条目,因为这才是最常发生的情况。
我对Python还比较陌生,需要一个实现方式,不要有太多的额外开销,以便尽可能快地更新数据。
有什么想法吗?谢谢!
1 个回答
1
curses 是用来在终端显示内容的首选工具。
#!/usr/bin/env python
import curses
import time
def updater():
fakedata = [[1, 78], [2, 97], [1, 45], [2, 2], [3, 89]]
codes_to_linenums_dict = {}
last_line = 0
win = curses.initscr()
for code, data in fakedata:
try:
# if we haven't seen this code before, give it the next line
if code not in codes_to_linenums_dict:
codes_to_linenums_dict[code] = last_line
last_line += 1
# use the line we set for this code.
line = codes_to_linenums_dict[code]
win.addstr(line, 0, '{}: {} '.format(code, data))
win.refresh()
# For display only
time.sleep(2)
except KeyboardInterrupt:
# if endwin isn't called the terminal becomes unuseable.
curses.endwin()
raise
curses.endwin()
if __name__ == '__main__':
updater()
~