终端 - 如何覆盖多行?

Terminal - How to overwrite many lines?

我想覆盖 hello。但是当打印 \n 时,我无法返回到该行。 那么像程序 htop.

这样覆盖很多行的应用程序做了什么?
import sys

print 'hello'
print 'huhu',
print '\r\r\rnooooo\r'

打印添加换行符。为此,最好直接写入标准输出。

 sys.stdout.write("mystring\r")

Linux 和 macOS 用户:

import time
import curses

stdscr = curses.initscr()

stdscr.addstr(0, 0, "Hello")

stdscr.refresh()
time.sleep(5)         # deliberate wait, else will automatically delete output
stdscr.addstr(0, 0, "huhu")
stdscr.refresh()

请参阅 Windows 用户的

colorama 第三方模块支持通过“\x1b[?:?H”命令字符串更改光标的位置。也可以这样清屏。

import colorama
colorama.init()
def put_cursor(x,y):
    print "\x1b[{};{}H".format(y+1,x+1)

def clear():
    print "\x1b[2J"

clear()
put_cursor(0,0)
print "hello"
print "huhu"
#return to first line
put_cursor(0,0)
print "noooooo"

该模块似乎通过导入 ctypes 并调用 windll.kernel32.SetConsoleCursorPosition 来执行此操作。参见 win32.py, line 58