【发布时间】:2021-02-24 16:46:59
【问题描述】:
我正在使用Live 显示来显示随时间增长的Table 的内容。最终会出现垂直溢出,在这种情况下,我希望最旧的(即最上面的)行消失,而最近的行应该与标题一起显示,即内容应该滚动。实时显示的vertical_overflow 参数提供了"visible" 选项,但这会使表格的标题消失。显然这是一个Table 特定的问题,因为标题应该保留但内容应该滚动。
import time
from rich.live import Live
from rich.table import Table
table = Table()
table.add_column('Time')
table.add_column('Message')
with Live(table, refresh_per_second=5, vertical_overflow='visible'):
for i in range(100):
time.sleep(0.2)
table.add_row(time.asctime(), f'Event {i:03d}')
左侧部分显示vertical_overflow='visible' 的行为,右侧部分显示所需的行为:
到目前为止,我正在使用一种解决方法,使用单独的数据结构来保存行,然后在每次添加新行时从头开始创建表。这似乎不是很有效,所以我想知道是否有更好的解决方案。对于多行行,此解决方法也失败,因为它将它们计为单行(因此会发生溢出)。
from collections import deque
import os
import time
from rich.live import Live
from rich.table import Table
def generate_table(rows):
table = Table()
table.add_column('Time')
table.add_column('Message')
for row in rows:
table.add_row(*row)
return table
width, height = os.get_terminal_size()
messages = deque(maxlen=height-4) # save space for header and footer
with Live(generate_table(messages), refresh_per_second=5) as live:
for i in range(100):
time.sleep(0.2)
messages.append((time.asctime(), f'Event {i:03d}'))
live.update(generate_table(messages))
【问题讨论】: