这已经被问过(例如 a , b 等),但我不能让它在 IPython 控制台中工作。 我只是想在同一行上一遍又一遍地打印一些文本,而不是作为连续文本,而是替换前一个文本。 这是我的代码:
import time
try:
while True:
s = "I want this always on the same line. "
print(s, end="\r", flush=True)
time.sleep(0.5)
except KeyboardInterrupt:
pass
这是我在 IPython 控制台中得到的:
我在 PC 和 Spyder 上使用 Anaconda 发行版,使用 Python 3。代码在 Anaconda 终端中运行,但我还需要打印一些图像,所以我需要 IPython。我还尝试使用 end="" 或在 print() 语句后添加逗号(即使这是针对 Python 2),但无济于事。
请您参考如下方法:
我在使用 IPython 控制台编辑之前写了这篇文章,所以我不确定这是否是一个可行的解决方案,但在这里它是:
我不使用 print() 命令,而是尝试使用 sys.stdout。
这是我的一个脚本中的“进度报告”:
from sys import stdout
from time import sleep
jobLen = 100
progressReport = 0
while progressReport < jobLen:
progressReport += 1
stdout.write("\r[%s/%s]" % (progressReport, jobLen))
stdout.flush()
sleep(0.1)
stdout.write("\n")
stdout.flush()
sleep函数只是为了让progresReport变大。 stdout 的“\r”部分是使脚本“替换”previus 字符串的原因。 flush() 添加在 write() 函数之后,因为有时需要在某些环境下显示输出。
一旦您不想再写入该行,则可以通过写入不带“\r”的空字符串或写入“\n”来终止它。
