python - 如何在python的终端顶部打印新输出?
问题描述
我怎么能在终端的顶部打印最新的输出,而不是不断地将新的输出添加到窗口的底部,而是堆叠在顶部?
示例程序:
for x in range(4):
print(x)
输出:
0
1
2
3
期望的输出:
3
2
1
0
编辑:这个例子只是一个简单的视觉效果,可以更好地理解这个问题。我的实际程序将实时返回数据,如果有意义的话,我有兴趣将最新的数据打印到顶部。
解决方案
使用 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[F
是ANSII Escape Code
将光标移动到上一行的开头。
笔记:
- 这不适用于所有类型的终端,但适用于 Windows
cmd
(正如我在您的标签中看到的那样)。 - 如果您需要使用
while
而不是for
保留一个计数器变量up_count=1
并在每次迭代结束时增加它。 - 这种方法适用于有限数量的行,但如果你想永远继续下去,你应该使用类似
curses
.
推荐阅读
- c# - 位图流到c#中的视频howto?
- java - 在包子目录中运行特定类的 main
- javascript - 根据 1 个特定值的标识将对象拆分为多个有序数组
- java - 如何防止执行在执行程序队列中等待空闲线程的任务
- c# - 如何在不取消整个控制器的情况下将方法从一个控制器授权给一个角色或多个角色
- c++ - 编译器如何在 C++ 中的多个主要函数之间进行选择?
- php - wordpress 作者页面可见性 / 404
- javascript - localStorage 似乎在 Angular 中不起作用
- laravel - 电子邮件不断从示例发送
- c++ - 后增量运算符如何与用户定义的类型一起使用?