Python: 如何在当前光标位置上方打印 n 行(当前行上方)

Python: how to print n lines above current cursor position (above current line)

假设我有

print("line1")
print("line2")
print("\n\n line3")

现在我想在“line2”上打印“line4”。

如何在 python 中只使用 print 函数?

您可以使用 ANSI 转义序列:wiki realpython

python中的CSI(控制序列引入子)是3[

因此,例如,您可以使用 Cursor Up (CUU) 序列,即 CSI 后跟 {n}A,其中 n 是您希望光标向上移动的次数。

所以通过定义

def cursorup(n):
    print(f"\r3[{n}A", end="")

任一

print("line1")
print("line2")
print("\n\n line3")
cursorup(3)
print("line4")

print("line1")
print("line2")
print("\n\n line3")
print("\r3[3A", end="")
print("line4")

会起作用。

\r就是做一个回车return,将光标移动到当前行的行首。 end="" 是为了让打印功能在打印后不会换行。

在任意位置写入输出的一种方法是使用另一个库,例如 curses