我怎么能在终端的顶部打印最新的输出,而不是不断地将新的输出添加到窗口的底部,而是堆叠在顶部?
示例程序:
for x in range(4):
print(x)
输出:
0
1
2
3
期望的输出:
3
2
1
0
编辑:这个例子只是一个简单的视觉效果,可以更好地理解这个问题。我的实际程序将实时返回数据,如果有意义的话,我有兴趣将最新的数据打印到顶部。
一种方法是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[F是ANSII Escape Code将光标移动到上一行的开头。
笔记:
cmd(正如我在您的标签中看到的那样)。while而不是for保留一个计数器变量up_count=1并在每次迭代结束时增加它。curses.你可以尝试使用这个
for x in list(range(4))[::-1]:
print(x)
看来您不能轻易反转终端顺序。
但是python你可以使用这个:
for i in reversed(range(10)):
print(i)
# Output
9
8
7
6
5
4
3
2
1
0