問題:
在控制台應用程式中,如何顯示進度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中文網其他相關文章!