Replace console output in Python

I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs.

I've got a loop doing things and the current output is along the lines of:

Doing thing 0
Doing thing 1
Doing thing 2
...

what would be neater would be to just have the last line update;

X things done.

I've seen this in a number of console programs and am wondering if/how I'd do this in Python.


Solution 1:

An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...

sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()

Slightly more sophisticated is a progress bar... this is something I am using:

def start_progress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
    sys.stdout.flush()
    progress_x = 0

def progress(x):
    global progress_x
    x = int(x * 40 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x

def end_progress():
    sys.stdout.write("#" * (40 - progress_x) + "]\n")
    sys.stdout.flush()

You call start_progress passing the description of the operation, then progress(x) where x is the percentage and finally end_progress()

Solution 2:

A more elegant solution could be:

def progress_bar(current, total, bar_length = 20):
    percent = float(current) * 100 / total
    arrow   = '-' * int(percent/100 * bar_length - 1) + '>'
    spaces  = ' ' * (bar_length - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')

call this function with value and endvalue, result should be

Progress: [------------->      ] 69 %

Note: Python 2.x version here.

Solution 3:

In python 3 you can do this to print on the same line:

print('', end='\r')

Especially useful to keep track of the latest update and progress.

I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.