I would like to overwrite something on a line above in a serial console. Is there a character that allows me to move up?
5 回答
大多数终端都理解ANSI 转义码。此用例的相关代码:
"\033[F"
– 将光标移动到上一行的开头"\033[A"
– 将光标上移一行
示例(Python):
print("\033[FMy text overwriting the previous line.")
No, not really easily, for that you'd have to use something like the curses library, especially if you want to have more control over cursor placement and do more things programatically.
Here's a link for the Python docs on Programming with Curses, and this short tutorial/example might be of interest too.
I just found this note in the docs in case you are using Windows:
No one has made a Windows port of the curses module. On a Windows platform, try the Console module written by Fredrik Lundh. The Console module provides cursor-addressable text output, plus full support for mouse and keyboard input, and is available from http://effbot.org/zone/console-index.htm.
I believe for C++ there is the NCurses library, the linked page has a section on moving the cursor if you want to poke around with C++. Also there's the NCurses Programming HowTo.
Long time ago I used the curses library with C quite successfully.
Update:
I missed the part about running this on a terminal/serially, for that the ANSI escape sequence, especially for a simple task like yours, will be easiest and I agree with @SvenMarnach solution for this.
for i in range(10):
print("Loading" + "." * i)
doSomeTimeConsumingProcessing()
sys.stdout.write("\033[F") # Cursor up one lin
在 Python 中尝试这个并用任何需要的例程替换 doSomeTimeConsumingProcessing(),希望它有所帮助
我可能错了,但是:
#include <windows.h>
void gotoxy ( int column, int line )
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle( STD_OUTPUT_HANDLE ),
coord
);
}
在 Windows 标准控制台中。
回车可用于转到行首,而 ANSI 代码ESC A
( "\033[A"
) 可将您带上一行。这适用于 Linux。它可以在 Windows 上使用该colorama
包启用 ANSI 代码:
import time
import sys
import colorama
colorama.init()
print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3 (no eol)", end="")
sys.stdout.flush()
time.sleep(1)
print("\rLine 3 the sequel")
time.sleep(1)
print("\033[ALine 3 the second sequel")
time.sleep(1)
print("\033[A\033[A\033[ALine 1 the sequel")
time.sleep(1)
print() # skip two lines so that lines 2 and 3 don't get overwritten by the next console prompt
print()
输出:
> python3 multiline.py
Line 1 the sequel
Line 2
Line 3 the second sequel
>
在幕后
,colorama 可能使用SetConsoleMode
.