找到一種合適的方法來視覺化終端中的下載和上傳進度而不擦除先前的輸出可能是一項常見任務。本文探討了用於建立進度條或類似的視覺化效果的 Python 解決方案,可輸出到控制台,同時保留先前的程式輸出。
對於通用進度條,您可以可以使用以下Python函數:
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()
# 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)
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 相容,請將以下內容新增至腳本頂部:
# -*- coding: utf-8 -*-
將進度條函數中的Python 3 字串格式替換為以下:
print('%\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd)
以上是如何使用 Python 在終端機中建立文字進度條?的詳細內容。更多資訊請關注PHP中文網其他相關文章!