是否有线上角色? (与\ n相反)

时间:2012-07-13 16:19:33

标签: python c++ terminal console

我想在串行控制台中覆盖上面一行的内容。是否有一个允许我向上移动的角色?

谢谢。

5 个答案:

答案 0 :(得分:61)

大多数终端都了解ANSI escape codes。转到上一行开头的代码是"\033[F"

答案 1 :(得分:9)

不,不是很容易,因为你必须使用像curses library这样的东西,特别是如果你想要更多地控制光标放置并以编程方式做更多的事情。

以下是Programming with Curses上Python文档的链接,这篇简短的tutorial/example也可能会引起人们的兴趣。

我刚刚在docs中找到了这个注释,以防您使用Windows:

  

没有人制作了curses模块的Windows端口。在Windows上   平台,尝试Fredrik Lundh编写的Console模块。控制台   模块提供光标可寻址文本输出,以及完全支持   鼠标和键盘输入,可从   http://effbot.org/zone/console-index.htm

我相信C ++中有NCurses库,如果您想要使用C ++,链接页面上有moving the cursor部分。还有NCurses Programming HowTo

很长时间以前我用C语言成功地使用了curses库。

<强>更新

我错过了关于在终端/串行上运行它的部分,因为ANSI转义序列,特别是对于像你这样的简单任务,将是最简单的,我同意@SvenMarnach解决方案。

答案 2 :(得分:2)

for i in range(10):  
    print("Loading" + "." * i) 

    doSomeTimeConsumingProcessing()

    sys.stdout.write("\033[F") # Cursor up one lin

在Python中尝试这个并用所需的任何例程替换doSomeTimeConsumingProcessing(),并希望它有所帮助

答案 3 :(得分:1)

我可能错了,但是:

#include <windows.h>


void gotoxy ( int column, int line )
{
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
}
在Windows标准控制台中

答案 4 :(得分:0)

回车符可以用于行首,而ANSI代码ESC A"\033[A")可以使您上一行。这适用于Linux。通过使用colorama包来启用ANSI代码,它可以在Windows上运行:

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启用了Console Virtual Terminal Sequences