控制台中的文本进度条[关闭]

  • 问题:

  • Want to improve this question? Update the question so it focuses on one problem only by editing this post.

    Closed 2 years ago.

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

    我希望应用程序显示一些可视化的下载/上传进度,每次下载数据块,我希望它提供一个进度更新,即使它只是一个数字表示,如百分比

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

    这似乎是一个相当常见的任务——我如何在保留之前的程序输出的同时,制作一个进度条或类似的可视化程序输出到我的控制台?在

  • 答案:
  • 以下是我经常使用的以下答案的汇总(不需要导入)

    注意:此答案中的所有代码都是为Python3创建的;要在Python2中使用此代码,请参阅答案末尾

    # 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(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
    # Print New Line on Complete
    if iteration == total:
    print()
    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

    评论中讨论了允许进度条根据终端窗口宽度动态调整的选项。虽然我不建议这样做,但这里有一个gist它实现了这个特性(并注意到了注意事项)

    下面的一条评论引用了answer在回答一个类似的问题。我喜欢它演示的易用性,并编写了一个类似的示例,但在添加了上面原始的printProgressBar函数的一些特性的同时,我选择不导入sys模块

    与上面的原始函数相比,这种方法的一些优点包括:取消了对函数的初始调用,以0%的速度打印进度条,并且使用enumerate成为可选的(即不再明确要求函数工作)

    def progressBar(iterable, 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)
    """
    total = len(iterable)
    # Progress Bar Printing Function
    def printProgressBar (iteration):
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
    # Initial Call
    printProgressBar(0)
    # Update Progress Bar
    for i, item in enumerate(iterable):
    yield item
    printProgressBar(i + 1)
    # Print New Line on Complete
    print()
    import time

    # A List of Items
    items = list(range(0, 57))

    # A Nicer, Single-Call Usage
    for item in progressBar(items, prefix = 'Progress:', suffix = 'Complete', length = 50):
    # Do stuff...
    time.sleep(0.1)
    Progress: |█████████████████████████████████████████████-----| 90.0% Complete

    要在Python 2中使用上述函数,请在脚本顶部将编码设置为UTF-8:

    # -*- coding: utf-8 -*-

    并替换字符串3中的字符串:

    print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)

    Python字符串2格式:

    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)