Skip to main content
ertius.org

python progress

The basic trick for doing "progress bars" at the (Unix) command line is this:

import sys
import time

for n in xrange(10):
    sys.stdout.write("\r")
    sys.stdout.write("{:2d}".format(n))
    sys.stdout.flush()
    time.sleep(1)

In this line, \r is a line-return - ie move the "cursor" back to the beginning of the line:

sys.stdout.write("\r")

Here we use string formatting to write some extra spaces before our number. In this case it doesn’t really matter, but if we were counting down we’d have to make sure we overwrote the extremes

sys.stdout.write("{:2d}".format(n))