Python控制终端/控制台中的输出位置

时间:2016-07-08 10:36:56

标签: python

这是python语言的问题,终端/控制台适用于类Unix系统。如果解决方案与平台无关,那将是很好的,但这不是必需的。

该方案是程序保持打印线到终端的时间。然而,在许多要打印的行中,有些行是特殊的,比如进度条或状态指示器:它们只能放在控制台的底部,而所有其他行仍然可以打印在通常的位置,一个之后另一个,屏幕也正常滚动。

示例代码解决方案比理论解决方案好得多。为此目的,这是一个例子:

def print_status(msg):
  # implement me
  print msg

def print_many_lines():
  print 'line one\n'
  print 'line two\n'
  print_status('i am here')
  print 'line three\n'
  print 'line four\n'
  print 'line five\n'
  print_status('i am changed')
  print 'line six\n'

您能帮我实现 print_status 功能,以便传递给它的 msg 将始终打印在终端的底部吗?

请注意,这与another similar question非常不同,当多个行连续打印到终端时,我们如何确保它们在同一行打印。使用\ r在这种情况下可能很有用,但它不能解决这个问题,因为(1)这些特殊的线可能不会连续打印,(2)在这些特殊线之后会打印出其他线,但这些特殊的线应该是仍然在终端的底部。

谢谢!

2 个答案:

答案 0 :(得分:3)

对于Windows终端,请尝试console module对于curses module执行的unix。{/ p>

这是在Windows上执行此操作的方法。

c = Console.getconsole()
c.text(0, -1, 'And this is the string at the bottom of the console')

通过为第二个参数指定-1,字符串位于底线。

对于Linux,一个在最后一行打印的工作代码。

import time
import curses

def pbar(window):
    height, width = window.getmaxyx()
    for i in range(10):
        window.addstr(height -1, 0, "[" + ("=" * i) + ">" + (" " * (10 - i )) + "]")
        window.refresh()
        time.sleep(0.5)

curses.wrapper(pbar)

答案 1 :(得分:0)

听起来你想使用curses库,它在Unix系统上处理基于文本的UI。在python的标准库中有一个模块:

https://docs.python.org/2/library/curses.html#module-curses

如何使用它在我害怕的范围内超出了答案的范围。

相关问题