2017-10-20 104 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