Home >Backend Development >Python Tutorial >How to Create a Customizable Terminal Text Progress Bar in Python without Overwriting Previous Output?

How to Create a Customizable Terminal Text Progress Bar in Python without Overwriting Previous Output?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 09:44:14191browse

How to Create a Customizable Terminal Text Progress Bar in Python without Overwriting Previous Output?

Terminal Text Progress Bar with Block Characters

Problem:

In a console application, how can one display a progress bar as files are uploaded or downloaded using ftplib, without disturbing previously printed text?

Solution:

To create a customizable progress bar that updates while preserving console output, consider the following:

Option 1: Single-Call

def progressBar(iterable, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"):
    """
    Single-call progress bar function.

    Args:
        iterable (Iterable): Iteratable object.
        prefix (str): Prefix string.
        suffix (str): Suffix string.
        decimals (int): Number of decimals in percent complete.
        length (int): Character length of bar.
        fill (str): Fill character.
        printEnd (str): End character.
    """
    total = len(iterable)

    def printProgressBar(iteration):
        percent = "{0:.{1}f}".format(100 * (iteration / float(total)), decimals)
        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()

Example Usage:

import time

items = list(range(57))

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

Option 2: Multiple Calls

def printProgressBar(iteration, total, prefix="", suffix="", decimals=1, length=100, fill="█", printEnd="\r"):
    """
    Progress bar printing function.

    Args:
        iteration (int): Current iteration.
        total (int): Total iterations.
        prefix (str): Prefix string.
        suffix (str): Suffix string.
        decimals (int): Number of decimals in percent complete.
        length (int): Character length of bar.
        fill (str): Fill character.
        printEnd (str): End character.
    """
    percent = "{0:.{1}f}".format(100 * (iteration / float(total)), decimals)
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + "-" * (length - filledLength)
    print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd)

    if iteration == total:
        print()

Example Usage:

import time

items = list(range(57))

# Initial call to print 0% progress
printProgressBar(0, len(items), prefix="Progress:", suffix="Complete", length=50)

for i, item in enumerate(items):
    # Do stuff...
    time.sleep(0.1)
    printProgressBar(i + 1, len(items), prefix="Progress:", suffix="Complete", length=50)

Both options provide customizable progress bars that dynamically update without overwriting prior console output.

The above is the detailed content of How to Create a Customizable Terminal Text Progress Bar in Python without Overwriting Previous Output?. 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