在终端python 2.7上的同一位置动态更新文本

时间:2018-07-19 13:13:47

标签: python python-2.7 dynamic console-output

我的程序是用Python 2.7编写的,我想进行动态更新。输出在表格视图中,具有数百个字符。我发现here是一个非常好的答案,但是它粉碎了100个以上的字符(如本文中所述)。而且,我不知道表格有多少行,它会动态变化。此外,我不想使用curses,因为我希望输出在控制台中内联,就像运行“ regular”命令一样

输出示例:

+------+--------------+-------------+
| Type |  IP Address  |    Status   |
+------+--------------+-------------+
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
+------+--------------+-------------+

我正在努力避免:

+------+--------------+-------------+
| Type |  IP Address  |    Status   |
+------+--------------+-------------+
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
+------+--------------+-------------+
+------+--------------+-------------+
| Type |  IP Address  |    Status   |
+------+--------------+-------------+
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
+------+--------------+-------------+
+------+--------------+-------------+
| Type |  IP Address  |    Status   |
+------+--------------+-------------+
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  aa  | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
| cccc | 10.11.10.10  | in Progress |
|  bb  | 10.11.10.10  | in Progress |
+------+--------------+-------------+

1 个答案:

答案 0 :(得分:0)

您可以使用ANSI代码上升多行。它应该在linux上工作:

import time
import sys

for i in range(0, 100):
  # print 4 lines
  print ("line 1\nline 2\nline 3")
  print (str(i))
  time.sleep(0.2)
  sys.stdout.write("\033[4A") # go up 4 lines

它将在某些终端中工作。它在Windows腻子中工作。如果您在腻子终端中返回的行数多了,它不会让您向上滚动文本,它将光标移至第一行。 Source of the ANSII code.