Home >Backend Development >Python Tutorial >How to Create a Text Progress Bar in Your Terminal Using Python?

How to Create a Text Progress Bar in Your Terminal Using Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 17:26:12678browse

How to Create a Text Progress Bar in Your Terminal Using Python?

Text Progress Bar in Terminal with Block Characters

Introduction

Creating a progress bar in the terminal can greatly enhance the user experience by providing a visual representation of a task's progress. However, maintaining the integrity of previous console output while updating the progress bar can be a challenge. This article explores how to create a progress bar in Python while preserving prior text.

Solution: Custom Progress Bar Function

Here's a reusable progress bar function that addresses the problem:

def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    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)
    if iteration == total:
        print()

Function Parameters:

Parameter Description
iteration Current iteration of the loop
total Total number of iterations
prefix Prefix text before the progress bar
suffix Suffix text after the progress bar
decimals Number of decimal places for percentage
length Width of the progress bar
fill Character used to fill the progress bar
printEnd End of line character (e.g., 'r')

Usage:

To use the progress bar, call the function within a loop:

total_items = 100

for item in range(total_items):
    # Do your processing here...
    printProgressBar(item + 1, total_items)

Single-Call Version:

For a simplified use case, consider this single-call version of the progress bar:

def progressBar(iterable, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    total = len(iterable)
    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)
    printProgressBar(0)
    for i, item in enumerate(iterable):
        yield item
        printProgressBar(i + 1)
    print()

for item in progressBar(range(100)):
    # Do your processing here...

This version requires no initial call to set the progress bar at 0% and accepts iterables as input.

Python 2 Compatibility:

For Python 2 compatibility, use the following code instead of Python 3 string formatting:

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

Conclusion:

By leveraging the provided functions, you can effortlessly integrate a text progress bar into your console applications while avoiding the erasure of prior text. The customizable parameters allow for a tailored progress bar appearance that fits your specific requirements.

The above is the detailed content of How to Create a Text Progress Bar in Your Terminal Using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn