I want to run a script, which basicly shows things like:
Installing XXX... [DONE]
Now, at the moment, I use print to print the whole line AFTER the function has succeeded. However, I now want it to print "Installing xxx..." first, and AFTER the function has run, to add the "DONE" tag; but on the same line.
Any ideas?
CORRECT ANSWER! You must use backspace '\r' or ('\x08') char to go back on previous position in console output
Python 3:
This code will count from 0% to 100% on one line. Final value will be:
Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?
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 octal015
[chr(0o15)
] or hexidecimal0d
[chr(0x0d)
] or decimal13
[chr(13)
]. Seeman 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 theCR
part ofCRLF
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 theprint
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 everyprint()
call.sys.stdout.flush
tells Python to flush the output of standard output, which is where you send output withprint()
unless you specify otherwise. You can also get the same behavior by running withpython -u
or setting environment variablePYTHONUNBUFFERED=1
, thereby skipping theimport sys
andsys.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.
Just in case you have pre-stored the values in an array, you can call them in the following format:
Print has an optional end argument, it is what printed in the end. The default is newline but you can change it to empty string. eg: print("hello world!", end="")
None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:
To test it:
"hello " will first print out and flush to the screen before the sleep. After that you can use standard print.
This simple example will print 1-10 on the same line.