No external packages. A ready-made piece of code.
You can customize bar progress symbol "#"
, bar size
, text prefix
etc.
Python 3.3+
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.3+
count = len(it)
def show(j):
x = int(size*j/count)
print("{}[{}{}] {}/{}".format(prefix, "#"*x, "."*(size-x), j, count),
end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
Usage:
import time
for i in progressbar(range(15), "Computing: ", 40):
time.sleep(0.1) # any code you need
To fill the whole character space use a unicode u"█"
char replacing "#"
. With for i in progressbar(range(100)): ...
you get :

Doesn't require a second thread. Some solutions/packages above require.
Works with any iterable it means anything that len()
can be used on. A list
, a dict
of anything for example ['a', 'b', 'c' ... 'g']
Works with generators only have to wrap it with a list(). For example for i in progressbar(list(your_generator), "Computing: ", 40):
Unless the work is done in the generator. In that case you need another solution (like tqdm).
You can also change output by changing out
to sys.stderr
for example.
Python 3.6+ (f-string)
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+
count = len(it)
def show(j):
x = int(size*j/count)
print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count}", end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
Python 2 (old-code)
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
out.write("%s[%s%s] %i/%i\r" % (prefix, u"#"*x, "."*(size-x), j, count))
out.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
out.write("\n")
out.flush()