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

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

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

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


当前回答

我写了一个简单的进度条:

def bar(total, current, length=10, prefix="", filler="#", space=" ", oncomp="", border="[]", suffix=""):
    if len(border) != 2:
        print("parameter 'border' must include exactly 2 symbols!")
        return None

    print(prefix + border[0] + (filler * int(current / total * length) +
                                      (space * (length - int(current / total * length)))) + border[1], suffix, "\r", end="")
    if total == current:
        if oncomp:
            print(prefix + border[0] + space * int(((length - len(oncomp)) / 2)) +
                  oncomp + space * int(((length - len(oncomp)) / 2)) + border[1], suffix)
        if not oncomp:
            print(prefix + border[0] + (filler * int(current / total * length) +
                                        (space * (length - int(current / total * length)))) + border[1], suffix)

正如你所看到的,它有:条的长度,前缀和后缀,填充,空间,文本在条上100%(oncomp)和边界

这里有一个例子:

from time import sleep, time
start_time = time()
for i in range(10):
    pref = str((i+1) * 10) + "% "
    complete_text = "done in %s sec" % str(round(time() - start_time))
    sleep(1)
    bar(10, i + 1, length=20, prefix=pref, oncomp=complete_text)

正在进行中:

30% [######              ]

Out on complete:

100% [   done in 9 sec   ] 

其他回答

Python 3

一个简单的,可定制的进度条

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

注意:这个答案中的所有代码都是为Python 3创建的;在python2中使用此代码请参见end of answer。

# 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

更新

在评论中有关于允许进度条动态调整终端窗口宽度的选项的讨论。虽然我不推荐这样做,但这里有一个实现该功能的要点(并注意注意事项)。

以上单次通话版本

下面的评论引用了一个类似问题的精彩答案。我喜欢它演示的易用性,并写了一个类似的,但选择不导入sys模块,而添加了上面原始printProgressBar函数的一些特性。

与上面的原始函数相比,这种方法的一些好处包括消除了对函数的初始调用,以0%打印进度条,并且枚举的使用变得可选(即不再显式地要求函数工作)。

def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create 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)
    # 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

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

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

并替换这一行中的Python 3字符串格式:

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

Python 2字符串格式化:

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

写入一个\r到控制台。这是一个“回车”,它使它之后的所有文本都在行首回显。喜欢的东西:

def update_progress(progress):
    print '\r[{0}] {1}%'.format('#'*(progress/10), progress)

这将给你一些像:[##########]100%

我正在使用来自reddit的进度。我喜欢它,因为它可以在一行中打印每一项的进度,而且它不应该从程序中删除打印输出。

编辑:固定链接

安装tqdm。(pip安装tqdm) 使用方法如下:

import time
from tqdm import tqdm
for i in tqdm(range(1000)):
    time.sleep(0.01)

这是一个10秒的进度条,输出如下内容:

47%|██████████████████▊                     | 470/1000 [00:04<00:05, 98.61it/s]
import sys
def progresssbar():
         for i in range(100):
            time.sleep(1)
            sys.stdout.write("%i\r" % i)

progressbar()

注意:如果你在交互式拦截器中运行这个,你会得到额外的数字打印出来