终端如何覆盖多行?

2024-10-01 09:34:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想覆盖hello。但是当一个\n被打印出来时,我就不能再回到那一行了。 那么,像htop程序这样覆盖许多行的应用程序会做些什么呢。在

import sys

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

Tags: import程序应用程序hellosysprinthtophuhu
3条回答

Print添加新行。为此,最好直接写stdout。在

 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用户,请参见other answer。在

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

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。在

相关问题 更多 >