【问题标题】:Dynamic update text in same place on terminal python 2.7终端python 2.7上同一位置的动态更新文本
【发布时间】:2018-12-27 15:35:26
【问题描述】:

我的程序是用 Python 2.7 编写的,我想做一个动态更新。输出是表格视图,有数百个字符。我找到了一个非常好的答案here,但是,它粉碎了 100 多个字符(如文章中所承诺的那样)。而且,我不知道表格有多少行,它是动态变化的。此外,我不想使用诅咒,因为我希望输出在控制台中内联,就像运行“常规”命令一样

输出示例:

+------+--------------+-------------+
| 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 |
+------+--------------+-------------+

【问题讨论】:

  • 你希望这个程序在什么操作系统上运行?
  • 操作系统是ubuntu16.04

标签: python python-2.7 dynamic console-output


【解决方案1】:

您可以使用 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.

【讨论】:

  • 感谢您的回答。即使命令在屏幕的 运行并且我已经多次更改行数,它也总是将 key-placer 放在顶部:从 1 行到 table length + n
  • 我不确定是ubuntu相关还是ssh终端
猜你喜欢
  • 2014-06-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2016-03-29
  • 1970-01-01
相关资源
最近更新 更多