4

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:

Text does not print on the same line

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.

Zep
  • 1,541
  • 13
  • 21

1 Answers1

4

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".

Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20
  • It works! I mean... it does not work with the actual code I am working with, but it works fine on my example. I'll try to figure out the rest. – Zep Oct 20 '17 at 13:47
  • Doesn't work in ipython as far as I can see. Or maybe it works in the terminal ipython console, I guess I am using it via a Jupyter notebook... – Ben Farmer Apr 06 '18 at 15:04