multiple prints on the same line in Python
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?
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.