2017-10-20 158 views
1

此之前已经被要求(例如ab等),但我不能让它在IPython中控制台工作。 我只是想在同一行上反复打印一些文本,而不是连续文本,而是替换前一个文本。 这是我的代码:打印在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的控制台:

Text does not print on the same line

我使用的PC和Spyder的蟒蛇分布,与Python 3代码在蟒蛇终端,但我需要打印出一些图像,所以我需要IPython。我也尝试使用end=""或在print()声明(即使这是Python 2)后添加逗号,但无济于事。

+1

'打印( “你好”,结束= “\ r”)'我的控制台(终端)上正常工作。 – ZdaR

+0

我得到 “hellohellohellohellohellohellohellohellohellohellohello” ... – Zep

+0

尝试运行它在终端,'python3 run.py' @Zep – ZdaR

回答

1

我的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() 

睡眠功能就是让你可以看到progresReport变大。 stdout的“\ r”部分是使脚本“替换”previus字符串的原因。 flush()在write()函数之后添加,因为有时需要在某些环境中显示输出。

一旦你不想写该行了,然后您可以通过不为“\ r”写一个空字符串也可以通过写“\ n”终止它。

+0

它的工作原理!我的意思是...它不适用于我正在使用的实际代码,但它对我的示例运行正常。我会试着找出其余的。 – Zep