How to Draw a Progress Bar in Python


In this example, we will learn how to draw a progress bar by updating the string with time with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# progressBarOfText.py

import sys, time

# define a progress bar
class ProgressBar:
    def __init__(self, count = 0, total = 0, width = 50):
        self.count = count
        self.total = total
        self.width = width

    # simulate the move of progress bar
    def move(self):
        self.count += 1
    
    # print the progress
    def log(self, s):
        sys.stdout.write(' ' * (self.width + 9) + 'r')
        sys.stdout.flush()
        print(s)

        progress = int(self.width * self.count / self.total)
        sys.stdout.write('{0:3}/{1:3}: '.format(self.count, self.total))
        sys.stdout.write('#' * progress + '-' * (self.width - progress) + 'r')
        
        if progress == self.width:
            sys.stdout.write('n')
        sys.stdout.flush()

def main():
    bar = ProgressBar(total = 10)
    for i in range(10):
        bar.move()
        bar.log('Current progress: ' + str(i + 1))
        time.sleep(1)

if __name__ == '__main__':
    main()

After running the codes, we can get these results:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement