multiple prints on the same line in Python

571,669

Solution 1

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

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

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?

Solution 4

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

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.

Share:
571,669

Related videos on Youtube

user697108
Author by

user697108

Updated on February 11, 2022

Comments

  • user697108
    user697108 over 1 year

    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?

  • mgilson
    mgilson almost 11 years
    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.
  • Prometheus
    Prometheus almost 9 years
    It works perfectly. Had only seen stdout solutions so far. Really good to know that.
  • Paddre
    Paddre over 8 years
    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
  • multipleinterfaces
    multipleinterfaces over 8 years
    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.
  • Turtles Are Cute
    Turtles Are Cute over 8 years
    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.
  • Vadim Zin4uk
    Vadim Zin4uk over 8 years
    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)
  • arjoonn
    arjoonn about 8 years
    This is in python 3. In python 2 you can simply print 'something',. The comma at the end prevents the addition of a newline.
  • Obi-Wan
    Obi-Wan about 7 years
    Thank you! Exactly what i needed aka .flush()
  • Martijn Pieters
    Martijn Pieters about 7 years
    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.
  • bjnortier
    bjnortier over 6 years
    The carriage return '\r' goes back to the beginning of the line, so the '* n' is unnecessary
  • Cory Madden
    Cory Madden over 6 years
    That print is incorrect syntax for Python 2.7 and the code doesn't work even with correct syntax.
  • Marc Cayuela
    Marc Cayuela about 6 years
    I think your answer is more suitable for: stackoverflow.com/questions/45263205/…
  • John
    John almost 6 years
    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)
  • Jesse Chisholm
    Jesse Chisholm over 4 years
    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).
  • FK82
    FK82 over 4 years
    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). ; )

Related