小编典典

控制台中的文本进度栏

python

我编写了一个简单的控制台应用程序,使用ftplib从FTP服务器上载和下载文件。

我希望该应用程序向用户展示其下载/上传进度的一些可视化;每次下载数据块时,我都希望它提供进度更新,即使它只是数字表示形式(如百分比)。

重要的是,我要避免擦除在前几行中已打印到控制台的所有文本(即,我不想在打印更新的进度时“清除”整个终端)。

这似乎是一项相当普通的任务-如何在保留先前程序输出的同时,制作进度条或类似的可视化内容输出到控制台?


阅读 452

收藏
2020-02-14

共1个答案

小编典典

一个简单的,可定制的进度条
以下是我经常使用的许多答案的汇总(不需要导入)。

# Print iterations progress
def 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", "\r\n") (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 Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(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

更新资料

注释中讨论了一个选项,该选项允许进度条动态调整为终端窗口宽度。尽管我不建议这样做,但是这里有一个实现此功能的要点(并注意了一些警告)。

2020-02-14