How to Print Out Status Bar and Percentage

How to print out status bar and percentage?

There's a Python module that you can get from PyPI called progressbar that implements such functionality. If you don't mind adding a dependency, it's a good solution. Otherwise, go with one of the other answers.

A simple example of how to use it:

import progressbar
from time import sleep
bar = progressbar.ProgressBar(maxval=20, \
widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
bar.start()
for i in xrange(20):
bar.update(i+1)
sleep(0.1)
bar.finish()

To install it, you can use easy_install progressbar, or pip install progressbar if you prefer pip.

How to show percentage along with progress bar in python?

Use sys.stdout.write() and \r to print a new string with the percentage and progress bar over the previous line each time.

import time
import sys

for x in range(21):
sys.stdout.write("\r{:>3}%\u2502{:<20}\u2502".format(x * 5, "\u2588" * x))
time.sleep(.05)

J to print out status bar and percentage

If I understand your question, you could use smoutput defined as 0 0 $ 1!:2&2 by the system to display your processing milestones on the screen

someverb =: 3 : 0
smoutput '{ }'
code
smoutput '{+++ }'
more code
smoutput '{+++++ }'
more code
smoutput '{++++++++}'
)

but you would have to know that the places that you insert the smoutput expressions would correspond to the amount of processing that had taken place.

As an example:

   test =: 3 : 0
​smoutput 6!:0 'hh:mm:ss.sss'
​6!:3 (2) NB. 2 second delay
​smoutput 6!:0 'hh:mm:ss.sss'
​6!:3 (2) NB. 2 second delay
​smoutput 6!:0 'hh:mm:ss.sss'
​)
test ''
14:53:42.313
14:53:44.317 NB. after two second delay
14:53:46.326 NB. after two second delay

or closer to the output you would like

test1 =: 3 : 0
start=. 6!:0 ''
smoutput '[ ] 0%'
6!:3 (2) NB. 2 second delay
smoutput '[=== ] 25%'
6!:3 (2) NB. 2 second delay
smoutput '[====== ] 50%'
6!:3 (4) NB. 4 second delay
smoutput '[============] 100%'
(6!:0 '')- start
)
test1 ''
[ ] 0%
[=== ] 25%
[====== ] 50%
[============] 100%
0 0 0 0 0 8.01821

Text progress bar in terminal with block characters

Python 3

A Simple, Customizable Progress Bar

Here's an aggregate of many of the answers below that I use regularly (no imports required).

Note: All code in this answer was created for Python 3; see end of answer to use this code with Python 2.

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
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)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Print New Line on Complete
if iteration == total:
print()

Sample Usage

import time

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
# Do stuff...
time.sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

Sample Output

Progress: |█████████████████████████████████████████████-----| 90.0% Complete

Update

There was discussion in the comments regarding an option that allows the progress bar to adjust dynamically to the terminal window width. While I don't recommend this, here's a gist that implements this feature (and notes the caveats).

Single-Call Version of The Above

A comment below referenced a nice answer posted in response to a similar question. I liked the ease of use it demonstrated and wrote a similar one, but opted to leave out the import of the sys module while adding in some of the features of the original printProgressBar function above.

Some benefits of this approach over the original function above include the elimination of an initial call to the function to print the progress bar at 0% and the use of enumerate becoming optional (i.e. it is no longer explicitly required to make the function work).

def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
Call in a loop to create terminal progress bar
@params:
iterable - Required : iterable object (Iterable)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
total = len(iterable)
# Progress Bar Printing Function
def printProgressBar (iteration):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Initial Call
printProgressBar(0)
# Update Progress Bar
for i, item in enumerate(iterable):
yield item
printProgressBar(i + 1)
# Print New Line on Complete
print()

Sample Usage

import time

# A List of Items
items = list(range(0, 57))

# A Nicer, Single-Call Usage
for item in progressBar(items, prefix = 'Progress:', suffix = 'Complete', length = 50):
# Do stuff...
time.sleep(0.1)

Sample Output

Progress: |█████████████████████████████████████████████-----| 90.0% Complete

Python 2

To use the above functions in Python 2, set the encoding to UTF-8 at the top of your script:

# -*- coding: utf-8 -*-

And replace the Python 3 string formatting in this line:

print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)

With Python 2 string formatting:

print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)

Python Progress Bar

There are specific libraries (like this one here) but maybe something very simple would do:

import time
import sys

toolbar_width = 40

# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['

for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()

sys.stdout.write("]\n") # this ends the progress bar

Note: progressbar2 is a fork of progressbar which hasn't been maintained in years.

Progress bar for a for loop in Python script

Using tqdm:

from tqdm import tqdm

for member in tqdm(members):
# current contents of your for loop

tqdm() takes members and iterates over it, but each time it yields a new member (between each iteration of the loop), it also updates a progress bar on your command line. That makes this actually quite similar to Matthias' solution (printing stuff at the end of each loop iteration), but the progressbar update logic is nicely encapsulated inside tqdm.

How to display a progress indicator in pure C/C++ (cout/printf)?

With a fixed width of your output, use something like the following:

float progress = 0.0;
while (progress < 1.0) {
int barWidth = 70;

std::cout << "[";
int pos = barWidth * progress;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << " %\r";
std::cout.flush();

progress += 0.16; // for demonstration only
}
std::cout << std::endl;

http://ideone.com/Yg8NKj

[>                                                                     ] 0 %
[===========> ] 15 %
[======================> ] 31 %
[=================================> ] 47 %
[============================================> ] 63 %
[========================================================> ] 80 %
[===================================================================> ] 96 %

Note that this output is shown one line below each other, but in a terminal emulator (I think also in Windows command line) it will be printed on the same line.

At the very end, don't forget to print a newline before printing more stuff.

If you want to remove the bar at the end, you have to overwrite it with spaces, to print something shorter like for example "Done.".

Also, the same can of course be done using printf in C; adapting the code above should be straight-forward.

How to make a still progress in python?

A pure solution using the end parameter of print():

The print() statement allows you to specify what last chars are printed at the end of the call. By default, end is set to '\r\n' which is a carriage return and newline. This moves the 'cursor' to the start of the next line which is what you would want in most cases.

However for a progress bar, you want to be able to print back over the bar so you can change the current position and percentage without the end result looking bad over multiple lines.

To do this, we need to set the end parameter to just a carriage return: '\r'. This will bring our current position back to the start of the line so we can re-print over the progress bar.

As a demonstration of how this could work, I made this simple little code that will increase the progress bar by 1% every 0.5 seconds. The key part of the code is the print statement so this is the part that you will probably take away and put into your main script.

import time, math

bl = 50 #the length of the bar
for p in range(101):
chars = math.ceil(p * (bl/100))
print('▮' * chars + '▯' * (bl-chars), str(p) + '%', end='\r')
time.sleep(0.5)

(n.b. the chars used here are copied from your question ('▮, ▯') and for me they did not print to the console in which case you will need to replace them with other ones for example: '█' and '.')

This code does what you want and steadily increases the percentage, here is an example of how it would look when p = 42:

▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▮▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯▯ 42%


Related Topics



Leave a reply



Submit