如何在将 header/column 名称保持在顶部的同时将行打印到命令行?

How to print lines to the command line whilst keeping the header/column names at the top?

如何将连续的数据流打印到标准输出,其中 header 列保持在 window 的顶部?

例如,不是以这种格式打印输出:

import random
while True:
    data = tuple(random.random() for i in range(4))
    print('Column A: %.3f, Column B: %.3f, Column C: %.3f, Column D: %.3f' % data)

Column A: 0.364, Column B: 0.311, Column C: 0.485, Column D: 0.272
Column A: 0.366, Column B: 0.619, Column C: 0.280, Column D: 0.305
Column A: 0.383, Column B: 0.119, Column C: 0.805, Column D: 0.778
Column A: 0.764, Column B: 0.957, Column C: 0.756, Column D: 0.849
Column A: 0.075, Column B: 0.909, Column C: 0.719, Column D: 0.749
Column A: 0.576, Column B: 0.165, Column C: 0.834, Column D: 0.529
Column A: 0.500, Column B: 0.404, Column C: 0.852, Column D: 0.782
Column A: 0.023, Column B: 0.681, Column C: 0.002, Column D: 0.713
Column A: 0.769, Column B: 0.523, Column C: 0.363, Column D: 0.044
Column A: 0.558, Column B: 0.892, Column C: 0.249, Column D: 0.854

如何以这种格式打印(无论打印多少行,最上面的 header 行都保留在屏幕上)?:

print('Column A\tColumn B\tColumn C\tColumn D')
while True:
    data = tuple(random.random() for i in range(4))
    print('%.3f\t\t%.3f\t\t%.3f\t\t%.3f' % data)

Column A    Column B    Column C    Column D
0.376       0.549       0.180       0.812
0.851       0.482       0.186       0.280
0.369       0.423       0.065       0.282
0.108       0.804       0.361       0.790
0.615       0.600       0.133       0.623
0.023       0.880       0.633       0.698
0.611       0.313       0.461       0.728
0.151       0.615       0.604       0.350
0.700       0.418       0.072       0.647
0.071       0.064       0.116       0.670

在此处排名 Python 业余爱好者,但我从您问题评论中的链接参考中获得灵感,并得出以下结论:

#!/usr/bin/env python
import random
import time
import urwid

def quit(*args, **kwargs):
    raise urwid.ExitMainLoop()

# The main callable
class EndlessRandom:
    def __call__(self):
        while True:
            data = tuple(random.random() for i in range(4))
            print('%.3f\t\t%.3f\t\t%.3f\t\t%.3f' % data)
            time.sleep(0.1)

# The components
title = urwid.Text("Column A\tColumn B\tColumn C\tColumn D".expandtabs(8))
body = urwid.Terminal(EndlessRandom())
urwid.connect_signal(body, 'closed', quit)

loop = urwid.MainLoop(urwid.Frame(body, title), handle_mouse=False, unhandled_input=quit)
body.main_loop = loop
loop.run()

它本质上是使用 urwid TUI library to create a "terminal with a titlebar", then wraps your random generator in a callable "factory" class for urwid.Terminal to 运行.

如果您还没有安装 urwid

pip install urwid

Ctrl-C 终止。