How To Implement Progress Bar With Percentage In Python Standard Output

In this article i will show you an example about how to implement progress bar in python console. It is useful when you write some python console program.

First let us look at the program execution result like below.

[                                                                                                    ]0%

[*                                                                                                   ]1%

[**                                                                                                  ]2%

......

[**************************************************************************************************  ]98%

[*************************************************************************************************** ]99%

[****************************************************************************************************]100%

Below is the source code, you can see code comments for more detail explain.

import time

''' the function will print out a progress bar in console. 

    bar_curr_num : is the current number of progress.

    bar_total_num : is the total number of progress bar.

'''
def build_progress_bar(bar_curr_num, bar_total_num):
    
    # first calculate the percentage of current progress.
    percentage = bar_curr_num / bar_total_num
    
    # get the percentage number.
    percentage_num = int(percentage * 100)
    
    # format the progress output text with above parameter's value.
    r = '\r[%s%s]%d%%' % ("*"*bar_curr_num, " "*(bar_total_num - bar_curr_num), percentage_num)
        
    # print out the progress bar in console.    
    print(r)
    

if __name__ == '__main__':
    
    # the progress bar total number is fixed to 100.
    bar_total_num = 100
    
    # loop in a range from 0 to bar_total_num
    for i in range(0, bar_total_num + 1):
        
        # thread sleep 0.1 second.
        time.sleep(0.1)
    
        # set current progress bar number.
        bar_curr_num = i
                
        # call progress_bar function to generate the progress bar.        
        build_progress_bar(bar_curr_num, bar_total_num)

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.