NeverAsleep - AlwaysAwake NeverAsleep - AlwaysAwake - 1 year ago 132
Python Question

Python command line loading bar

I have seen a few different loading bars that are displayed in the terminal however, some of them rely on \r which does not seem to work and it may be because I use python 2.7 rather than 3.X.

I have got a loading bar but it prints a new line each time.

def update_progress(progress):
print"\r [{0}] {1}%".format('#'*(progress/10), progress)

while prog != 101:
prog = prog + 1`

I am very new to python so if you can make the code short and understandable if possible. This may look like a duplicate question but some others on Stack Overflow do not work or print on new lines.

If \r is supposed to work on python 2.7 then could you explain how to fix it as it does not work. However, this confuses me as \n works perfectly fine but that is another issue.

P.S: I also need it to clear the line before printing again.


Answer Source

Besides the fact that you never initialize prog (I suppose you want
prog = 0 before the while loop) you can suppress the printing of a newline-character in Python2 by putting a comma after the statement:

def update_progress(progress):
    print "\r [{0}] {1}%".format('#'*(progress//10), progress),

However, that comma is hard to miss when reading the code, so importing and using the Python 3 print function is better.

from __future__ import print_function

def update_progress(progress):
    print("\r [{0}] {1}%".format('#'*(progress//10), progress), end='')