The Python Oracle

Text progress bar in terminal with block characters

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC E Schuberts Piano Sonata D 784 in A

--

Chapters
00:00 Question
00:52 Accepted answer (Score 707)
04:20 Answer 2 (Score 334)
04:38 Answer 3 (Score 238)
05:04 Answer 4 (Score 126)
05:29 Thank you

--

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

Accepted answer links:
[gist]: https://gist.github.com/greenstick/b23e4...
[answer]: https://stackoverflow.com/a/34482761/220...

Answer 3 links:
[tqdm: add a progress meter to your loops in a second]: https://github.com/tqdm/tqdm
[image]: https://i.stack.imgur.com/SQB5z.gif

Answer 4 links:
["carriage return"]: http://en.wikipedia.org/wiki/Carriage_re...

--

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