The Python Oracle

Text progress bar in terminal with block characters

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life

--

Chapters
00:00 Text Progress Bar In Terminal With Block Characters
00:39 Answer 1 Score 131
01:06 Answer 2 Score 342
01:21 Answer 3 Score 251
01:38 Answer 4 Score 85
01:57 Thank you

--

Full question
https://stackoverflow.com/questions/3173...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #console #progress #updating

#avk47



ANSWER 1

Score 342


Writing '\r' will move the cursor back to the beginning of the line.

This displays a percentage counter:

import time
import sys

for i in range(101):
    time.sleep(0.05)
    sys.stdout.write("\r%d%%" % i)
    sys.stdout.flush()



ANSWER 2

Score 251


tqdm: add a progress meter to your loops in a second:

>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
...     time.sleep(1)
... 
|###-------| 35/100  35% [elapsed: 00:35 left: 01:05,  1.00 iters/sec]

tqdm repl session




ANSWER 3

Score 131


Write a \r to the console. That is a "carriage return" which causes all text after it to be echoed at the beginning of the line. Something like:

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

which will give you something like: [ ########## ] 100%




ANSWER 4

Score 85


It is less than 10 lines of code.

The gist here: https://gist.github.com/vladignatyev/06860ec2040cb497f0f3

import sys


def progress(count, total, suffix=''):
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
    sys.stdout.flush()  # As suggested by Rom Ruben

enter image description here