在 Python 的控制台上取消打印一行?

Unprint a line on the console in Python?

是否可以操纵已经打印到控制台的文本行?

例如,

import time
for k in range(1,100):
     print(str(k)+"/"+"100")
     time.sleep(0.03)
     #>> Clear the most recent line printed to the console
print("ready or not here I come!")

我已经看到一些在 Windows 下使用自定义 DOS 控制台的东西,但我真的很喜欢在 command_line 上工作的东西,就像在没有任何额外画布的情况下打印一样。

这个存在吗?如果没有,为什么不呢?

P.S.: 我试图使用 curses,这导致我在 Python 之外的命令行行为出现问题。 (在错误出带有 curses 的 Python 脚本后,我的 Bash shell 停止打印换行符 -unacceptable- )。

您要找的是:

print("{}/100".format(k), "\r", end="")

\r是回车return,return将光标移到行首。实际上,无论打印什么都会覆盖之前打印的文本。 end=""是防止打印后\n(保持在同一行)。

sonrad10:

中建议的更简单的形式
print("{}/100".format(k), end="\r")

在这里,我们只是将结束字符替换为 \r 而不是 \n

Python 2 中,同样可以通过以下方式实现:

print "{}/100".format(k), "\r",

您需要的是 ANSI 命令代码。 http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
您还需要代码来激活 ANSI 命令代码。我会使用 Colorama。 https://pypi.python.org/pypi/colorama

使用curses (Python 3.4+) 模块。

最简单的方法(至少对于 Python 2.7)是使用语法:

print 'message', '\r',
print 'this new message now covers the previous'

请注意第一个打印末尾的额外“,”。这使得打印保持在同一行。同时,'\r' 将打印内容放在该行的开头。所以第二个打印语句会覆盖第一个。