Skip to content

Instantly share code, notes, and snippets.

@aubricus
Last active Jul 12, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@aubricus 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 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 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 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 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 maxgalbu commented Jun 26, 2017

It's missing an import sys at the beginning

@rapier83

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@georgetz15 georgetz15 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 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 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 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 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 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 chitter99 commented May 3, 2019

I like apple

@paablux

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@simonthor simonthor commented Jun 7, 2020

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

@aubricus

This comment has been minimized.

Copy link
Owner Author

@aubricus aubricus commented Jun 8, 2020

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

@simonthor

This comment has been minimized.

Copy link

@simonthor simonthor commented Jun 8, 2020

@aubricus thanks!

@smangels

This comment has been minimized.

Copy link

@smangels smangels commented Jun 12, 2020

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