Issue
This has been asked before (for instance a, b, etc.), but I cannot make it work in IPython console. I simply want to print some text over and over on the same line, not as continuous text, but replacing the previous one. This is my code:
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
And here is what I get in IPython console:
I am using Anaconda distribution on PC and Spyder, with Python 3. The code works in Anaconda terminal, but I need to print out some image as well so I need IPython. I also tried using end=""
or adding a comma after the print()
statement (even if this is for Python 2), but to no avail.
Solution
I wrote this before the edit with IPython console, so I am not sure if this is a solution that works there or not, but here it its:
Instead of using the print() command, i would instead try to use sys.stdout.
This is a "progressreport" that I have in one of my scripts:
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()
The sleep function is just so that you can see the progresReport get larger. The "\r" part of the stdout is what makes the script "replace" the previus string. The flush() is added after the write() function, because it is sometimes needed to show the output on some enviroments.
Once you don't want to write to that row anymore, then you terminate it either by writing an empty string without "\r" or by writing a "\n".
Answered By - Hampus Larsson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.