multiple prints on the same line in Python
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.
Related videos on Youtube
user697108
Updated on February 11, 2022Comments
-
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?
-
Cees Timmerman almost 7 yearsPossible duplicate of How do I keep Python print from adding newlines or spaces?
-
ideasman42 over 6 yearsAnswers to this question don't mention that sometimes you want to clear the line, see: stackoverflow.com/questions/45263205
-
-
mgilson almost 11 yearsI 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 almost 9 yearsIt works perfectly. Had only seen stdout solutions so far. Really good to know that.
-
Paddre over 8 yearsThis 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 over 8 yearsThat 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 over 8 yearsTo 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 over 8 yearsbouth 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 about 8 yearsThis 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 about 7 yearsThank you! Exactly what i needed aka .flush()
-
Martijn Pieters about 7 yearsWithout a newline, you probably want to explicitly flush the buffer. Use
print("...", end="", flush=True)
in Python 3, in Python 2 add asys.stdout.flush()
call. -
bjnortier over 6 yearsThe carriage return '\r' goes back to the beginning of the line, so the '* n' is unnecessary
-
Cory Madden over 6 yearsThat
print
is incorrect syntax for Python 2.7 and the code doesn't work even with correct syntax. -
Marc Cayuela about 6 yearsI think your answer is more suitable for: stackoverflow.com/questions/45263205/…
-
John almost 6 yearsin 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 over 4 yearsIf you want to overwrite the line, then instead of
end=""
putend="\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 withstr.ljust(longest)
. -
FK82 over 4 yearsJust 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). ; )