在 IPython 控制台中的同一位置打印

Print on the same spot in IPython console

之前有人问过这个问题(例如 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。

这是我的一个脚本中的 "progressreport":

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”部分使脚本 "replace" 成为 previus 字符串。 flush()添加在write()函数之后,因为在某些环境下有时需要显示输出。

一旦您不想再写入该行,则可以通过写入不带“\r”的空字符串或写入“\n”来终止它。