285

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

How can I instead print Installing xxx... and [DONE] on the same line?


For the specific problem of writing a new message on the same line, replacing what was there before, please see How to overwrite the previous print to stdout?. Most answers here interpreted the question as being about writing new text at the end of the current line.

For the problem of using a single print to output multiple things at once, see How can I print multiple things (fixed text and/or variable values) on the same line, all at once?.

2

18 Answers 18

336

Python 3 Solution

The print() function accepts an end parameter which defaults to \n (new line). Setting it to an empty string prevents it from issuing a new line at the end of the line.

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

Python 2 Solution

Putting a comma on the end of the print() line prevents print() from issuing a new line (you should note that there will be an extra space at the end of the output).

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"
8
  • 2
    It works perfectly. Had only seen stdout solutions so far. Really good to know that.
    – Prometheus
    Commented Jan 8, 2015 at 7:59
  • 5
    This doesn't work if you have both prints and a time consuming action in between (all in the same function / indentation level). Before the action starts, there is no output at all and after it is finished the output appears as whole
    – Paddre
    Commented Feb 20, 2015 at 15:08
  • 2
    That is probably more a function of the output buffering preformed by the OS for the process as a whole, which is not a python-specific problem. See stackoverflow.com/questions/107705 for a python-specific workaround. Commented Feb 20, 2015 at 16:48
  • 18
    Without a newline, you probably want to explicitly flush the buffer. Use print("...", end="", flush=True) in Python 3, in Python 2 add a sys.stdout.flush() call.
    – Martijn Pieters
    Commented Nov 3, 2016 at 12:53
  • 12
    in python 3.x you'll want to add a "\r" to end to replace the printed line VS appending to the end of it print("Progress: {}%".format(var), end="\r", flush=True)
    – John
    Commented Jan 6, 2018 at 22:42
110

You can simply use this:

print 'something',
...
print ' else',

and the output will be

something else

no need to overkill by import sys. Pay attention to comma symbol at the end.

Python 3+ print("some string", end=""); to remove the newline insert at the end. Read more by help(print);

10
  • 3
    Note there are two spaces by using this method
    – ethanjyx
    Commented Nov 12, 2013 at 3:20
  • 1
    This is the simplest and the most efficient answer.
    – gixxer
    Commented May 22, 2015 at 4:45
  • This does not work when arguments of print are in parentheses. This works: <print "hello",; print("hello")> but this doesnt work <print("hello",); print("hello")> Commented Nov 27, 2015 at 7:46
  • @MayankJaiswal This does work with the parens. print('hello'),
    – drglove
    Commented Feb 6, 2016 at 22:39
  • 1
    print function has slightly different syntax in python 2 VS 3.
    – magnump0
    Commented Feb 7, 2016 at 4:24
68

You should use backspace '\r' or ('\x08') char to go back on previous position in console output

Python 2+:

import time
import sys

def backspace(n):
    sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(s)                     # just print
    sys.stdout.flush()                      # needed for flush when using \x08
    backspace(len(s))                       # back n chars    
    time.sleep(0.2)                         # sleep for 200ms

Python 3:

import time   

def backline():        
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print(s, end='')                        # just print and flush
    backline()                              # back to the beginning of line    
    time.sleep(0.2)                         # sleep for 200ms

This code will count from 0% to 100% on one line. Final value will be:

> python test.py
100%

Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?

3
  • 1
    To clarify, it looks like the commented-out code in this example is for Python 2, and the non-commented lines are for Python 3. Commented Mar 9, 2015 at 23:05
  • 1
    bouth lines will work fine in Python 3. If you use '\x08' as a backspace you need to flush the output stream - print((b'\x08' * n).decode(), end='', flush=True) Commented Mar 10, 2015 at 9:43
  • 1
    The carriage return '\r' goes back to the beginning of the line, so the '* n' is unnecessary
    – bjnortier
    Commented May 8, 2017 at 8:02
42

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

1
  • 4
    I personally prefer this solution to the higher voted one because it works the exact same way on python2.x and python3.x without needing to rely on __future__ imports or anything like that.
    – mgilson
    Commented Jan 31, 2013 at 14:29
30

Most simple:

Python 3

    print('\r' + 'something to be override', end='')

It means it will back the cursor to beginning, than will print something and will end in the same line. If in a loop it will start printing in the same place it starts.

2
  • 3
    Cool! Works in Windows as well. Commented Feb 13, 2019 at 11:59
  • 3
    Thanks this works fine for me! I think that print(’something to be override’, end=‘\r’) is simpler, though.
    – Tropilio
    Commented Apr 10, 2019 at 9:00
18

None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:

def print_no_newline(string):
    import sys
    sys.stdout.write(string)
    sys.stdout.flush()

To test it:

import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')

"hello " will first print out and flush to the screen before the sleep. After that you can use standard print.

1
  • 2
    Thank you! Exactly what i needed aka .flush()
    – Obi-Wan
    Commented Oct 20, 2016 at 12:28
13

sys.stdout.write will print without return carriage

import sys
sys.stdout.write("installing xxx")
sys.stdout.write(".")

http://en.wikibooks.org/wiki/Python_Programming/Input_and_output#printing_without_commas_or_newlines

11

Python appends newline as an end to print. Use end=' ' for python3 for print method to append a space instead of a newline. for python2 use comma at end of print statement.

print('Foo', end=' ')
print('Bar')
9

This simple example will print 1-10 on the same line.

for i in range(1,11):
    print (i, end=" ")
9

Print has an optional end argument, it is what printed in the end. The default is a newline, but you can change it to empty string. e.g. print("hello world!", end="")

1
  • 2
    This is in python 3. In python 2 you can simply print 'something',. The comma at the end prevents the addition of a newline.
    – arjoonn
    Commented Sep 6, 2015 at 5:37
4

If you want to overwrite the previous line (rather than continually adding to it), you can combine \r with print(), at the end of the print statement. For example,

from time import sleep

for i in xrange(0, 10):
    print("\r{0}".format(i)),
    sleep(.5)

print("...DONE!")

will count 0 to 9, replacing the old number in the console. The "...DONE!" will print on the same line as the last counter, 9.

In your case for the OP, this would allow the console to display percent complete of the install as a "progress bar", where you can define a begin and end character position, and update the markers in between.

print("Installing |XXXXXX              | 30%"),
4

Here a 2.7-compatible version derived from the 3.0 version by @Vadim-Zin4uk:

Python 2

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print '{0}\r'.format(s),                # just print and flush

    time.sleep(0.2)

For that matter, the 3.0 solution provided looks a little bloated. For example, the backspace method doesn't make use of the integer argument and could probably be done away with altogether.

Python 3

import time

for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    print('{0}\r'.format(s), end='')        # just print and flush

    time.sleep(0.2)                         # sleep for 200ms

Both have been tested and work.

2

This is a very old thread, but here's a very thorough answer and sample code.

\r is the string representation of Carriage Return from the ASCII character set. It's the same as octal 015 [chr(0o15)] or hexidecimal 0d [chr(0x0d)] or decimal 13 [chr(13)]. See man ascii for a boring read. It (\r) is a pretty portable representation and is easy enough for people to read. It very simply means to move the carriage on the typewriter all the way back to the start without advancing the paper. It's the CR part of CRLF which means Carriage Return and Line Feed.

print() is a function in Python 3. In Python 2 (any version that you'd be interested in using), print can be forced into a function by importing its definition from the __future__ module. The benefit of the print function is that you can specify what to print at the end, overriding the default behavior of \n to print a newline at the end of every print() call.

sys.stdout.flush tells Python to flush the output of standard output, which is where you send output with print() unless you specify otherwise. You can also get the same behavior by running with python -u or setting environment variable PYTHONUNBUFFERED=1, thereby skipping the import sys and sys.stdout.flush() calls. The amount you gain by doing that is almost exactly zero and isn't very easy to debug if you conveniently forget that you have to do that step before your application behaves properly.

And a sample. Note that this runs perfectly in Python 2 or 3.

from __future__ import print_function

import sys
import time

ANS = 42
FACTORS = {n for n in range(1, ANS + 1) if ANS % n == 0}

for i in range(1, ANS + 1):
    if i in FACTORS:
        print('\r{0:d}'.format(i), end='')
        sys.stdout.flush()
        time.sleep(ANS / 100.0)
else:
    print()
1
2

This solution in Python 3.X specific:

When I need to do this, I'll generally just use

end=' '

For example:

# end='' ends the output with a <space> 
print("Welcome to" , end = ' ') 
print("stackoverflow", end = ' ')

This outputs as:

Welcome to stackoverflow

The space in end= can be replaced with any character. For example,

print("Welcome to" , end = '...') 
print("stackoverflow", end = '!')

Which outputs as:

Welcome to...stackoverflow!
2

print() has a built in parameter "end" that is by default set to "\n" Calling print("This is America") is actually calling print("This is America", end = "\n"). An easy way to do is to call print("This is America", end ="")

1

Just in case you have pre-stored the values in an array, you can call them in the following format:

for i in range(0,n):
       print arr[i],
0

Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

The example they provide:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

For printing the on the same line, as others have suggested, just use end=""

-3

I found this solution, and it's working on Python 2.7

# Working on Python 2.7 Linux

import time
import sys


def backspace(n):
    print('\r', end='')                     # use '\r' to go back


for i in range(101):                        # for 0 to 100
    s = str(i) + '%'                        # string for output
    sys.stdout.write(string)
    backspace(len(s))                       # back for n chars
    sys.stdout.flush()
    time.sleep(0.2)                         # sleep for 200ms
1
  • 1
    That print is incorrect syntax for Python 2.7 and the code doesn't work even with correct syntax. Commented Aug 6, 2017 at 20:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.