How to animate the command line?

One way to do this is to repeatedly update the line of text with the current progress. For example:

def status(percent):
    sys.stdout.write("%3d%%\r" % percent)
    sys.stdout.flush()

Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints “\r\n” (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).

Leave a Comment