Skip to content

Instantly share code, notes, and snippets.

@aubricus
Last active May 17, 2024 21:09
Show Gist options
  • Save aubricus/f91fb55dc6ba5557fbab06119420dd6a to your computer and use it in GitHub Desktop.
Save aubricus/f91fb55dc6ba5557fbab06119420dd6a to your computer and use it in GitHub Desktop.
Python Progress Bar
Copyright 2020 Aubrey Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# -*- 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
Copy link
Author

aubricus commented Nov 7, 2016

Additional Notes:

  • Default encoding is necessary only for Python 2.x

@chuchro3
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
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
Copy link

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

@maxgalbu
Copy link

It's missing an import sys at the beginning

@rapier83
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)

@georgetz15
Copy link

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
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
Copy link

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
Copy link

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
Copy link

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

@albertoivo
Copy link

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
Copy link

I like apple

@paablux
Copy link

paablux 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.

@simonthor
Copy link

Does this code have a license (e.g. MIT, GPL v3)? Or can I just use it however I want?

@aubricus
Copy link
Author

aubricus commented Jun 8, 2020

@simonthor I've updated it with an MIT lic.

@simonthor
Copy link

simonthor commented Jun 8, 2020

@aubricus thanks!

@smangels
Copy link

I like a more restraint version of the progress bar :-)

=> |============>--------------------------------------------------------------------| 14.7%

Below you will find the code that prepares the bar string in order to achieve the result shown above

bar = '=' * filled_length + '>' + '-' * (bar_length - filled_length)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment