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

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

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 17:52:13364browse

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

Text Progress Bar in Terminal with Block Characters

Introduction

Many terminal-based applications require a way to visualize progress. In this article, we will explore how to create a progress bar in a terminal using block characters while preserving prior output.

Customizable Progress Bar

The following code provides a customizable progress bar that can be used with any Python 3 application:

def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    percent = ("{0:.{0}f}".format(decimals)).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 completion
    if iteration == total:
        print()

Single-Call Version

For convenience, the following code provides a single-call version of the above progress bar:

def progressBar(iterable, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    total = len(iterable)
    
    # Progress bar printing function
    def printProgressBar(iteration):
        percent = ("{0:.{0}f}".format(decimals)).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 completion
    print()

Usage

The following code shows how to use the progress bar:

import time

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

# Progress bar usage
for item in progressBar(items, prefix='Progress:', suffix='Complete', length=50):
    # Do stuff...
    time.sleep(0.1)

Conclusion

These code snippets provide a versatile and easy-to-use progress bar solution that can enhance the user experience of any terminal-based application.

The above is the detailed content of How to Create a Customizable 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