终端 - 如何覆盖多行?

use*_*510 4 python python-2.7

我想覆盖hello.但是当\n打印出来时我无法回到那条线上.那么应用程序做了什么来覆盖许多行,如程序htop.

import sys

print 'hello'
print 'huhu',
print '\r\r\rnooooo\r'
Run Code Online (Sandbox Code Playgroud)

Bha*_*Rao 6

对于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()
Run Code Online (Sandbox Code Playgroud)

请参阅Windows用户的其他答案.

  • 即使OP使用的是Windows,也不要删除.它可能对将来有用. (2认同)

Kev*_*vin 6

彩色光第三方模块具有用于改变光标的位置,通过支承"\ 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"
Run Code Online (Sandbox Code Playgroud)

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