Print to the same line and not a new line?

139,166

Solution 1

It's called the carriage return, or \r

Use

print i/len(some_list)*100," percent complete         \r",

The comma prevents print from adding a newline. (and the spaces will keep the line clear from prior output)

Also, don't forget to terminate with a print "" to get at least a finalizing newline!

Solution 2

For me, what worked was a combo of Remi's and siriusd's answers:

from __future__ import print_function
import sys

print(str, end='\r')
sys.stdout.flush()

Solution 3

From python 3.x you can do:

print('bla bla', end='')

(which can also be used in Python 2.6 or 2.7 by putting from __future__ import print_function at the top of your script/module)

Python console progressbar example:

import time

# status generator
def range_with_status(total):
    """ iterate from 0 to total and show progress in console """
    n=0
    while n<total:
        done = '#'*(n+1)
        todo = '-'*(total-n-1)
        s = '<{0}>'.format(done+todo)
        if not todo:
            s+='\n'        
        if n>0:
            s = '\r'+s
        print(s, end='')
        yield n
        n+=1

# example for use of status generator
for i in range_with_status(10):
    time.sleep(0.1)

Solution 4

In Python 3.3+ you don’t need sys.stdout.flush(). print(string, end='', flush=True) works.

So

print('foo', end='')
print('\rbar', end='', flush=True)

will overwrite ‘foo’ with ‘bar’.

Solution 5

for Console you'll probably need

sys.stdout.flush()

to force update. I think using , in print will block stdout from flushing and somehow it won't update

Share:
139,166

Related videos on Youtube

chriscauley
Author by

chriscauley

Updated on April 23, 2021

Comments

  • chriscauley
    chriscauley almost 3 years

    Basically I want to do the opposite of what this guy did... hehe.

    Python Script: Print new line each time to shell rather than update existing line

    I have a program that is telling me how far along it is.

    for i in some_list:
        #do a bunch of stuff.
        print i/len(some_list)*100," percent complete"
    

    So if len(some_list) was 50, I'd get that last line printed 50 times over. I want to print one line and keep updating that line. I know I know this is probably the lamest question you'll read all day. I just can't figure out the four words I need to put into google to get the answer.

    Update! I tried mvds' suggestion which SEEMED right. The new code

    print percent_complete,"           \r",
    

    Percent complete is just a string (I was abstracting the first time now I an trying to be literal). The result now is that it runs the program, doesn't print ANYTHING until after the program is over, and then prints "100 percent complete" on one and only one line.

    Without the carriage return (but with the comma, half of mvds' suggestion) it prints nothing until the end. And then prints:

    0 percent complete     2 percent complete     3 percent complete     4 percent complete    
    

    And so on. So now the new issue is that with the comma it doesn't print until the program is finished.

    With the carriage return and no comma it behaves the exact same as with neither.

    • mvds
      mvds over 13 years
      the background is, btw, that in several languages the \n (which we now omit) serves as an implicit signal to flush to stdout. For otherwise a lot of people will be confused.
  • Nicholas Knight
    Nicholas Knight over 13 years
    Just make sure you're always printing the same amount of data (or more than any previous print) to the line, otherwise you'll end up with cruft at the end.
  • Nicholas Knight
    Nicholas Knight over 13 years
    @dustynachos: Heh, forgot about that wrinkle. See the Python Output Buffering question: stackoverflow.com/questions/107705/python-output-buffering
  • Nicholas Knight
    Nicholas Knight over 13 years
    @dustynachos: (or just use sys.stdout.flush() after each print call, that may actually be better if you don't care about output buffering for the rest of your program)
  • fccoelho
    fccoelho almost 11 years
    The \r appears to add a new line as well
  • Bryce Guinta
    Bryce Guinta almost 8 years
    Terminator was only refreshing the line every 30 seconds when using print("...", end='\r') for me unless I ran this command immediately after the print statement. Thanks
  • bgenchel
    bgenchel almost 6 years
    this doesn't work for me. I've actually tried this numerous times and it has never worked for me. I'm using iterm2 on a mac, but i'm ssh'd into a linux server most of the time. I've never found a method to do this that actually works.
  • bgenchel
    bgenchel almost 6 years
    this gets rid of the newline, but does not allow overwriting, which I think is what the author wants.
  • bli
    bli about 4 years
    It works, provided the printed text ends with a "\r".
  • z33k
    z33k about 4 years
    This was the only working solution for me (Python 3.8, Windows, PyCharm).
  • Milo Wielondek
    Milo Wielondek over 3 years
    @bgenchel used with '\r' (as in code sample) it does exactly what OP wants
  • DaveR
    DaveR over 3 years
    simplest and cleanest option for python => 3.6
  • Ra Rot
    Ra Rot over 3 years
    Outdated.. As of Python 3.8.5 for me only that works: print("some string", end='\r')
  • trinity420
    trinity420 over 3 years
    It works for me in debug run but not on normal run without debugger, very strange.. As it would not flush but it should.
  • Vaidøtas I.
    Vaidøtas I. over 2 years
    just adding end='\r' is enough :), thanks!

Related