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

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

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

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


当前回答

检查这个库:clint

它有很多功能,包括一个进度条:

from time import sleep  
from random import random  
from clint.textui import progress  
if __name__ == '__main__':
    for i in progress.bar(range(100)):
        sleep(random() * 0.2)

    for i in progress.dots(range(100)):
        sleep(random() * 0.2)

此链接提供了其功能的快速概述

其他回答

python终端进度条代码

import sys
import time

max_length = 5
at_length = max_length
empty = "-"
used = "%"

bar = empty * max_length

for i in range(0, max_length):
    at_length -= 1

    #setting empty and full spots
    bar = used * i
    bar = bar+empty * at_length

    #\r is carriage return(sets cursor position in terminal to start of line)
    #\0 character escape

    sys.stdout.write("[{}]\0\r".format(bar))
    sys.stdout.flush()

    #do your stuff here instead of time.sleep
    time.sleep(1)

sys.stdout.write("\n")
sys.stdout.flush()

并且,为了添加到堆中,这里有一个你可以使用的对象:

将以下内容添加到新文件progressbar.py中

import sys

class ProgressBar(object):
    CHAR_ON  = '='
    CHAR_OFF = ' '

    def __init__(self, end=100, length=65):
        self._end = end
        self._length = length
        self._chars = None
        self._value = 0

    @property
    def value(self):
        return self._value
    
    @value.setter
    def value(self, value):
        self._value = max(0, min(value, self._end))
        if self._chars != (c := int(self._length * (self._value / self._end))):
            self._chars = c
            sys.stdout.write("\r  {:3n}% [{}{}]".format(
                int((self._value / self._end) * 100.0),
                self.CHAR_ON  * int(self._chars),
                self.CHAR_OFF * int(self._length - self._chars),
            ))
            sys.stdout.flush()

    def __enter__(self):
        self.value = 0
        return self

    def __exit__(self, *args, **kwargs):
        sys.stdout.write('\n')

可以包含在您的程序中:

import time
from progressbar import ProgressBar

count = 150
print("starting things:")

with ProgressBar(count) as bar:
    for i in range(count + 1):
        bar.value += 1
        time.sleep(0.01)

print("done")

结果:

starting things:
  100% [=================================================================]
done

这可能有点“夸张”,但如果经常使用,就很方便了。

函数从Greenstick 2.7:

def printProgressBar (iteration, total, prefix = '', suffix = '',decimals = 1, length = 100, fill = '#'):

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),
sys.stdout.flush()
# Print New Line on Complete                                                                                                                                                                                                              
if iteration == total:
    print()

https://pypi.python.org/pypi/progressbar2/3.30.2

Progressbar2是一个很好的基于ascii的命令行progressbar库 导入的时间 进口progressbar

bar = progressbar.ProgressBar()
for i in bar(range(100)):
    time.sleep(0.02)
bar.finish()

https://pypi.python.org/pypi/tqdm

TQDM是progressbar2的替代方案,我认为它用于pip3,但我不确定

from tqdm import tqdm
for i in tqdm(range(10000)):
...

http://code.activestate.com/recipes/168639-progress-bar-class/ (2002) http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/ (2004) http://pypi.python.org/pypi/progressbar (2006)

还有很多教程等着你去谷歌。