Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Progress Bar
# -*- coding: utf-8 -*-
# Print iterations progress
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
bar_length - Optional : character length of bar (Int)
"""
str_format = "{0:." + str(decimals) + "f}"
percents = str_format.format(100 * (iteration / float(total)))
filled_length = int(round(bar_length * iteration / float(total)))
bar = '█' * filled_length + '-' * (bar_length - filled_length)
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
@aubricus

This comment has been minimized.

Copy link
Owner Author

aubricus commented Nov 3, 2016

Minor edits from this snippet on StackOverflow

  • Fix some PEP8 errors
  • Add default encoding to fix error with non-ascii character
@aubricus

This comment has been minimized.

Copy link
Owner Author

aubricus commented Nov 7, 2016

Additional Notes:

  • Default encoding is necessary only for Python 2.x
@chuchro3

This comment has been minimized.

Copy link

chuchro3 commented Mar 6, 2017

Thanks for this!

One thing that may be worth noting is if your loop is going from a standard 0-indexed range say, 'i in range(0, N)', the iteration you should pass is i+1. This made the difference of my total percentage being 99.9% vs 100.0% when complete. I just modified the function to add 1 to iteration at the start since I believe this is the most common use case.

@bonheml

This comment has been minimized.

Copy link

bonheml commented Mar 30, 2017

Thanks for this gist !
It was very helpfull for me. I encountered a little display bug because the suffix argument had not always the same length. Longer suffix still appears when a smaller one is displayed after it.
I fixed it by clearing the line before printing again like this
sys.stdout.write('\x1b[2K\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))

@marcospedreiro

This comment has been minimized.

Copy link

marcospedreiro commented May 25, 2017

Awesome, thanks! For those who want more details, checkout: https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console

@maxgalbu

This comment has been minimized.

Copy link

maxgalbu commented Jun 26, 2017

It's missing an import sys at the beginning

@rapier83

This comment has been minimized.

Copy link

rapier83 commented Aug 20, 2017

First of all, it's so nice function. thank you
It can convert to f-string style in 3.6+


percents = f'{100 * (iteration / float(total)):.2f}'
#"{0:." + str(decimals) + "f}"
#percents = str_format.format(100 * (iteration / float(total)))

filled_length = int(round(bar_length * iteration / float(total)))
bar = f'{"█" * filled_length}{"-" * (bar_length - filled_length)}'
#'█' * filled_length + '-' * (bar_length - filled_length)

sys.stdout.write(f'\r{prefix} |{bar}| {percents}% {suffix}'),
#'\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)
@FFF-Fox

This comment has been minimized.

Copy link

FFF-Fox commented Aug 29, 2017

Thank you very much man! This is a very nice function for updating the user on progress visually. As @maxgalby already commented, you need to add import sys at the beginning.

@ahertel

This comment has been minimized.

Copy link

ahertel commented Oct 15, 2017

Hi
I am using and loving your progress bar but wanted to tweak a little bit to give more detail as to what it is doing while in the process of completing the progress bar.
I added a parameter to your function called "current_task" to do this but I can't get it to print out as desired.
when I call_ print_progress(7,10,...remaining params, "downloading contacts") i would like it to print this

Currently downloading contacts
Progress |████████████████████████████████-------------------------| 70% Complete

and then when i call i call print_progress(8,10,...remaining params, "downloading companies")
i would like it to change in place to now look like this

Currently downloading companies
Progress |████████████████████████████████████----------------| 80% Complete

How can I change your code to do this? @aubricus

@dunatotatos

This comment has been minimized.

Copy link

dunatotatos commented Nov 7, 2017

Having the \r character at the end of the printed line would allow to have any other message (Warning, Info, ...) displayed on top of the progress bar instead of being overwritten.

With sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)),, a call like
progress_bar(1, 10)
print("Info: 1 file loaded")
progress_bar(2, 10)

would give:
|█---------| 1%
|██--------| 2%

With sys.stdout.write('%s |%s| %s%s %s\r' % (prefix, bar, percents, '%', suffix)),, the same calls would give:
Info: 1 file loaded
|██--------| 2%

@palimondo

This comment has been minimized.

Copy link

palimondo commented Feb 17, 2018

I have been using this with suffix showing the name of currently processed item. Because the names had different lengths, garbage was accumulating at the end. To solve this I have used ANSI escape sequence '\033[K' (Clear to the end of line). You can also make multiline progress bar when you also use '\033[F' (Cursor up one line).

for i in range(10): 
    print_progress(i, 9, '\033[Fprefix', '\nsuffix\033[K’)

Don’t forget to put extra \n before first use, so that you don’t overwrite your previous output.

@mtbiker-s

This comment has been minimized.

Copy link

mtbiker-s commented Mar 27, 2018

This is such a clever function! Totally dig it! Thank you for sharing!

@albertoivo

This comment has been minimized.

Copy link

albertoivo commented Apr 28, 2018

I have a really long query in the database. I would like to run this progress bar while the query is running. How to do this in python?

@chitter99

This comment has been minimized.

Copy link

chitter99 commented May 3, 2019

I like apple

@pabarv

This comment has been minimized.

Copy link

pabarv commented May 8, 2019

I have a really long query in the database. I would like to run this progress bar while the query is running. How to do this in python?

I don't think that's really possible. The thing that can do is measure the time takes to execute the query.
In order to print some progress bar you have to have a fix number.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.