I want to run a script, which basically shows an output like this:
Installing XXX... [DONE]
Currently, I print Installi
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=""
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
This simple example will print 1-10 on the same line.
for i in range(1,11):
print (i, end=" ")
You can use the print
statement to do this without importing sys
.
def install_xxx():
print "Installing XXX... ",
install_xxx()
print "[DONE]"
The 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).
The Python 3 Solution
Since the above does not work in Python 3, you can do this instead (again, without importing sys
):
def install_xxx():
print("Installing XXX... ", end="", flush=True)
install_xxx()
print("[DONE]")
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.
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%"),