繁体   English   中英

使用打印删除python中的当前行

[英]delete current line in python with print

我正在 python 中执行代码并希望通过重写输出上的当前行来更新我的状态。 例子:

import time

print("1 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("2 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("3 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("BBBB")
print("c")

现在这个代码的输出是

BBBBa a
c

如何更改我的代码以获得以下输出?

BBBB
c

谢谢你。

\\r只移动光标; 本身没有删除文本,它只是提供了机会,覆盖现有文本。

你尝试的几乎任何东西都依赖于终端,但通常你使用的是使用ANSI 转义序列的 一种这样的序列用于清除当前行。

import time

print("\x1b[K1 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[K2 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[K3 a a a", end="\r")
time.sleep(1) #placeholder for doing stuff
print("\x1b[KBBBB")
print("c")

\\x1b[K从当前光标位置清除到当前行的末尾。

ncurses这样的库可用于独立于终端的屏幕处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM