【问题标题】:Print on the same spot in IPython console在 IPython 控制台中的同一位置打印
【发布时间】:2017-10-20 07:36:14
【问题描述】:

以前有人问过这个问题(例如ab 等),但我无法使其在 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 上使用 Python 3 上的 Anaconda 发行版。代码在 Anaconda 终端中工作,但我还需要打印一些图像,所以我需要 IPython。我还尝试使用end="" 或在print() 语句后添加逗号(即使这是针对Python 2),但无济于事。

【问题讨论】:

  • print("hello", end="\r") 在我的控制台(终端)上运行良好。
  • 我得到“hellohellohellohellohellohellohellohellohellohellohello”...
  • 尝试在终端中运行它,python3 run.py@Zep
  • 啊!回车确实在终端有效!但我需要使用 IPython,因为我也想输出一些图像......我将编辑问题

标签: python printing console ipython


【解决方案1】:

我在使用 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()

睡眠功能只是为了让你可以看到进度报告变大。标准输出的“\r”部分是使脚本“替换”前一个字符串的原因。在 write() 函数之后添加了 flush(),因为有时需要在某些环境中显示输出。

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

【讨论】:

  • 有效!我的意思是......它不适用于我正在使用的实际代码,但它在我的示例中运行良好。我会尽力弄清楚其余的。
  • 据我所知,在 ipython 中不起作用。或者它可以在终端 ipython 控制台中工作,我想我是通过 Jupyter 笔记本使用它...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 2017-11-30
  • 2019-04-04
  • 2022-07-22
  • 2018-07-20
  • 1970-01-01
相关资源
最近更新 更多