找到一种合适的方法来可视化终端中的下载和上传进度而不擦除以前的输出可能是一项常见任务。本文探讨了用于创建进度条或类似的可视化效果的 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中文网其他相关文章!