首頁 >後端開發 >Python教學 >如何在 Python 中建立可自訂的終端文字進度條而不覆蓋先前的輸出?

如何在 Python 中建立可自訂的終端文字進度條而不覆蓋先前的輸出?

Patricia Arquette
Patricia Arquette原創
2024-12-03 09:44:14112瀏覽

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

帶有區塊字元的終端文字進度條

問題:

在控制台應用程式中,如何顯示進度bar 使用ftplib上傳或下載文件,不會幹擾先前列印的內容

解決方案:

要建立在保留控制台輸出的同時更新的可自訂進度條,請考慮以下內容:

選項 1 :單次呼叫

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()

範例用法:

import time

items = list(range(57))

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

選項2:多次呼叫

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()

用法範例:

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)

兩個選項都提供可自訂的進度條,可以動態更新而不會覆蓋先前的控制台輸出。

以上是如何在 Python 中建立可自訂的終端文字進度條而不覆蓋先前的輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn