281

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user697108
  • 3,521
  • 3
  • 20
  • 14
  • 2
    Possible duplicate of [How do I keep Python print from adding newlines or spaces?](http://stackoverflow.com/questions/255147/how-do-i-keep-python-print-from-adding-newlines-or-spaces) – Cees Timmerman Dec 09 '16 at 02:21
  • 1
    Answers to this question don't mention that sometimes you want to clear the line, see: https://stackoverflow.com/questions/45263205 – ideasman42 Jul 23 '17 at 09:44

18 Answers18

331

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]"
Wouter
  • 534
  • 3
  • 14
  • 22
multipleinterfaces
  • 8,913
  • 4
  • 30
  • 34
  • 2
    It works perfectly. Had only seen stdout solutions so far. Really good to know that. – Prometheus Jan 08 '15 at 07: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 Feb 20 '15 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 http://stackoverflow.com/questions/107705 for a python-specific workaround. – multipleinterfaces Feb 20 '15 at 16:48
  • 17
    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 Nov 03 '16 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 Jan 06 '18 at 22:42
  • If you want to overwrite the line, then instead of `end=""` put `end="\r"` so the cursor starts over again. or in python 2, append `"\r"` to your string. Watch for short lines leaving kruft. May want to pad with `str.ljust(longest)`. – Jesse Chisholm Feb 14 '19 at 19:28
  • Just in case someone also stumbles upon this: you also have to adjust the length of the printed string to fit into a terminal line. Otherwise, none of the methods in this thread will work (at least not on macOS 10.13). ; ) – FK82 Mar 08 '19 at 07:26
  • If one needs to keep "printing" at the same line (i.e. multiple `print()`), `\r` must be prepended. For example, `print(f"\r* [{file}] Line {l_idx} [{len(line)}]", end="", flush=True)`. – JoyfulPanda Oct 19 '22 at 12:36
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);

boldnik
  • 2,547
  • 2
  • 27
  • 32
66

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?

Tropilio
  • 1,395
  • 1
  • 9
  • 27
Vadim Zin4uk
  • 1,716
  • 22
  • 18
  • 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. – Turtles Are Cute Mar 09 '15 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) – Vadim Zin4uk Mar 10 '15 at 09:43
  • 1
    The carriage return '\r' goes back to the beginning of the line, so the '* n' is unnecessary – bjnortier May 08 '17 at 08: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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
ferostar
  • 7,074
  • 7
  • 38
  • 61
  • 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 Jan 31 '13 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.

Community
  • 1
  • 1
Sunfloro
  • 730
  • 1
  • 8
  • 12
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.

hyprnick
  • 2,643
  • 2
  • 21
  • 18
14

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

John Giotta
  • 16,432
  • 7
  • 52
  • 82
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')
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
MrKulli
  • 735
  • 10
  • 19
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="")

kaya3
  • 47,440
  • 4
  • 68
  • 97
TulkinRB
  • 590
  • 1
  • 6
  • 10
  • 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 Sep 06 '15 at 05:37
9

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

for i in range(1,11):
    print (i, end=" ")
Umali Leonard
  • 91
  • 1
  • 1
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%"),
Brian Bunker
  • 105
  • 2
  • 6
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.

Dannid
  • 1,507
  • 1
  • 20
  • 17
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()
  • I think your answer is more suitable for: https://stackoverflow.com/questions/45263205/python-how-to-print-on-same-line-clearing-previous-text – Marc Cayuela Oct 25 '17 at 19:06
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 ="")

Ryan Lee
  • 339
  • 2
  • 8
Miles Mbo
  • 21
  • 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!
Dharman
  • 30,962
  • 25
  • 85
  • 135
alio
  • 154
  • 6
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],
k20392
  • 11
  • 1
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=""

Mircea
  • 954
  • 1
  • 13
  • 17
-2

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
ideasman42
  • 42,413
  • 44
  • 197
  • 320
Luis Silva
  • 9
  • 1
  • 3