multiple prints on the same line in Python

PythonPrintingStdoutLine Breaks

Python Problem Overview


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

However, I now want to print Installing xxx... and [DONE] on the same line.

Any ideas?

Python Solutions


Solution 1 - Python

The Python 3 Solution

The print function accepts an end parameter which defaults to "\n". 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]")

Pyhton 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]"

Solution 2 - Python

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);

Solution 3 - Python

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: https://stackoverflow.com/questions/14047372/why-do-python-print-statements-that-contain-end-arguments-behave-differently

Solution 4 - Python

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.

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

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

Solution 8 - Python

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')

Solution 9 - Python

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="")

Solution 10 - Python

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

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

Solution 11 - Python

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%"),

Solution 12 - Python

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.

Solution 13 - Python

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()

Solution 14 - Python

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 ="")

Solution 15 - Python

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!

Solution 16 - Python

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],

Solution 17 - Python

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

Solution 18 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser697108View Question on Stackoverflow
Solution 1 - PythonmultipleinterfacesView Answer on Stackoverflow
Solution 2 - PythonboldnikView Answer on Stackoverflow
Solution 3 - PythonVadim Zin4ukView Answer on Stackoverflow
Solution 4 - PythonferostarView Answer on Stackoverflow
Solution 5 - PythonSunfloroView Answer on Stackoverflow
Solution 6 - PythonhyprnickView Answer on Stackoverflow
Solution 7 - PythonJohn GiottaView Answer on Stackoverflow
Solution 8 - PythonMrKulliView Answer on Stackoverflow
Solution 9 - PythonTulkinRBView Answer on Stackoverflow
Solution 10 - PythonUmali LeonardView Answer on Stackoverflow
Solution 11 - PythonBrian BunkerView Answer on Stackoverflow
Solution 12 - PythonDannidView Answer on Stackoverflow
Solution 13 - PythonChris CosbyView Answer on Stackoverflow
Solution 14 - PythonMiles MboView Answer on Stackoverflow
Solution 15 - PythonalioView Answer on Stackoverflow
Solution 16 - Pythonk20392View Answer on Stackoverflow
Solution 17 - PythonMirceaView Answer on Stackoverflow
Solution 18 - PythonLuis SilvaView Answer on Stackoverflow