首页 > 解决方案 > 如何在python的终端顶部打印新输出?

问题描述

我怎么能在终端的顶部打印最新的输出,而不是不断地将新的输出添加到窗口的底部,而是堆叠在顶部?

示例程序:

for x in range(4):
    print(x)

输出:

0
1
2
3

期望的输出:

3
2
1
0

编辑:这个例子只是一个简单的视觉效果,可以更好地理解这个问题。我的实际程序将实时返回数据,如果有意义的话,我有兴趣将最新的数据打印到顶部。

标签: pythonwindowscmdprintingterminal

解决方案


使用 ANSII 转义码移动光标

一种方法是go-up-to-beginnig为每行继续打印适当数量的 ANSII 转义字符,但这意味着,您需要在每次迭代中存储项目:

historical_output = []
padding = -1
UP = '\033[F'

for up_count, x in enumerate(range(4), start=1):
    curr_len = len(str(x))

    if curr_len > padding:
        padding = curr_len

    historical_output.insert(0, x)
    print(UP * up_count)
    print(*historical_output, sep='\n'.rjust(padding))

输出:

3
2
1
0

将输出限制为特定行数

如果要将输出限制为最后n几行,可以使用collections.deque

from collections import deque

max_lines_to_display = 5        # If this is None, falls back to above code
historical_output = deque(maxlen=max_lines_to_display)
padding = -1
up_count = 1
UP = '\033[F'

for x in range(12):
    curr_len = len(str(x))

    if curr_len > padding:
        padding = curr_len

    historical_output.appendleft(x)
    print(UP * up_count)

    if (max_lines_to_display is None 
        or up_count < max_lines_to_display+1):
        up_count += 1

    print(*historical_output, sep='\n'.rjust(padding))

输出:

11
10
9
8
7

\033[FANSII Escape Code将光标移动到上一行的开头。

笔记:

  • 这不适用于所有类型的终端,但适用于 Windows cmd(正如我在您的标签中看到的那样)。
  • 如果您需要使用while而不是for保留一个计数器变量up_count=1并在每次迭代结束时增加它。
  • 这种方法适用于有限数量的行,但如果你想永远继续下去,你应该使用类似curses.

推荐阅读