一个简单的,可定制的进度条
以下是我经常使用的许多答案的汇总(不需要导入)。
# Print iterations progressdef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "r"): """ Call in a loop to create 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", "rn") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd) # Print New Line on Complete if iteration == total: print()注意:这是针对Python 3的;有关在Python 2中使用此功能的详细信息,请参见注释。
样品用量
import time# A List of Itemsitems = list(range(0, 57))l = len(items)# Initial call to print 0% progressprintProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)for i, item in enumerate(items): # Do stuff... time.sleep(0.1) # Update Progress Bar printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
样本输出:
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
更新资料
注释中讨论了一个选项,该选项允许进度条动态调整为终端窗口宽度。尽管我不建议这样做,但是这里有一个实现此功能的要点(并注意了一些警告)。



