如何在将标题/列名保持在顶部的同时将行打印到命令行?

时间:2019-02-13 06:08:17

标签: python python-3.x stdout

如何将连续的数据流打印到标准输出,其中标题栏保持在窗口顶部?

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

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

如何以这种格式打印(无论打印多少行,顶部标题行都会保留在屏幕上)?

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

1 个答案:

答案 0 :(得分:1)

此处是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库创建“带有标题栏的终端”,然后将随机生成器包装在callable“ factory”类中,以便urwid.Terminal运行。 / p>

如果尚未安装urwid

pip install urwid

Ctrl-C 终止。