Home >Backend Development >Python Tutorial >How Can I Create a Text Progress Bar in the Terminal Using Python?

How Can I Create a Text Progress Bar in the Terminal Using Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 07:58:10528browse

How Can I Create a Text Progress Bar in the Terminal Using Python?

Text Progress Bar in Terminal with Block Characters

Finding a suitable method for visualizing download and upload progress in the terminal without erasing previous output can be a common task. This article explores Python solutions for creating a progress bar or similar visualization that outputs to the console while preserving prior program output.

Simple, Customizable Progress Bar

For a general-purpose progress bar, you can use the following Python function:

def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    """
    Call in a loop to create a terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:.{dec}f}".format(100 * (iteration / float(total)), dec=decimals))
    filledLength = int(length * iteration / total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd)
    if iteration == total:
        print()

Sample Usage:

# A List of Items
items = list(range(0, 57))
l = len(items)

printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=50)
for i, item in enumerate(items):
    # Do stuff...

    # Update Progress Bar
    printProgressBar(i + 1, l, prefix='Progress:', suffix='Complete', length=50)

Single-Call Version:

def progressBar(iterable, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'):
    """
    Call in a loop to create a terminal progress bar
    @params:
        iterable    - Required  : iterable object (Iterable)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    total = len(iterable)

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

Python 2 Compatibility:

For compatibility with Python 2, add the following to the top of your script:

# -*- coding: utf-8 -*-

Replace the Python 3 string formatting in the progress bar function with the following:

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

The above is the detailed content of How Can I Create a Text Progress Bar in the 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