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

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

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

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


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

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

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


下面是一个用Python编写的进度条的好例子:http://nadiana.com/animated-terminal-progress-bar-in-python

但如果你想自己写。你可以使用curses模块让事情变得更简单:)

(编辑) 也许更容易不是诅咒这个词。但是如果你想创建一个成熟的cui,那么curses会为你照顾很多东西。

(编辑) 由于旧的链接已经失效,我已经发布了我自己的Python Progressbar版本,请在这里获取:https://github.com/WoLpH/python-progressbar


写入'\r'将把光标移回行首。

这将显示一个百分比计数器:

import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" % i)
    sys.stdout.flush()

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)

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


在Python命令行运行这个命令(不是在任何IDE或开发环境中):

>>> import threading
>>> for i in range(50+1):
...   threading._sleep(0.5)
...   print "\r%3d" % i, ('='*i)+('-'*(50-i)),

在我的Windows系统上运行良好。


import sys
def progresssbar():
         for i in range(100):
            time.sleep(1)
            sys.stdout.write("%i\r" % i)

progressbar()

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


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

编辑:固定链接


检查这个库: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)

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


我意识到我在游戏中迟到了,但这里是我写的一个稍微有点yum风格的(Red Hat)(这里不是100%的准确性,但如果你使用进度条来达到这个准确度,那么你就错了):

import sys

def cli_progress_test(end_val, bar_length=20):
    for i in xrange(0, end_val):
        percent = float(i) / end_val
        hashes = '#' * int(round(percent * bar_length))
        spaces = ' ' * (bar_length - len(hashes))
        sys.stdout.write("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
        sys.stdout.flush()

应该产生如下所示的结果:

Percent: [##############      ] 69%

... 括号保持不变,只有哈希值增加。

作为装饰器,这可能会更好。再等一天……


哈哈,我刚刚为此写了一整篇文章 这里的代码请记住,你不能使用unicode时做块ASCII我使用cp437

import os
import time
def load(left_side, right_side, length, time):
    x = 0
    y = ""
    print "\r"
    while x < length:
        space = length - len(y)
        space = " " * space
        z = left + y + space + right
        print "\r", z,
        y += "█"
        time.sleep(time)
        x += 1
    cls()

你就这么叫它

print "loading something awesome"
load("|", "|", 10, .01)

它看起来是这样的

loading something awesome
|█████     |

根据上面的答案和其他类似的关于CLI进度条的问题,我想我得到了一个普遍的答案。请登录https://stackoverflow.com/a/15860757/2254146查看。

总之,代码是这样的:

import time, sys

# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
    barLength = 10 # Modify this to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = "Halt...\r\n"
    if progress >= 1:
        progress = 1
        status = "Done...\r\n"
    block = int(round(barLength*progress))
    text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status)
    sys.stdout.write(text)
    sys.stdout.flush()

看起来像

百分比:[##########]99.0%


根据上面的建议,我制作了进度条。

然而,我想指出一些缺点

每次刷新进度条时,它将从新一行开始 打印(‘\ r({0}){1} %’。格式('#' * progress* 10, progress)) 是这样的: [] 0% [#] 10% (# #) 20% (# # #) 30%

2.方括号“]”和右边的百分数随着“###”变长而右移。 3.如果表达式'progress / 10'不能返回整数,则会发生错误。

下面的代码将修复上面的问题。

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

好吧,这里是工作的代码,我在发布之前测试了它:

import sys
def prg(prog, fillchar, emptchar):
    fillt = 0
    emptt = 20
    if prog < 100 and prog > 0:
        prog2 = prog/5
        fillt = fillt + prog2
        emptt = emptt - prog2
        sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%")
        sys.stdout.flush()
    elif prog >= 100:
        prog = 100
        prog2 = prog/5
        fillt = fillt + prog2
        emptt = emptt - prog2
        sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nDone!")
        sys.stdout.flush()
    elif prog < 0:
        prog = 0
        prog2 = prog/5
        fillt = fillt + prog2
        emptt = emptt - prog2
        sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nHalted!")
        sys.stdout.flush()

优点:

20个字符条(每5个字符对应1个字符) 自定义填充字符 自定义空字符 暂停(任何低于0的数字) 完成(100及100以上的任何数字) 进度计数(0-100(以下和以上用于特殊功能)) 条形图旁边的百分数,这是一条单线

缺点:

仅支持整数(但可以通过将除法改为整数除法来支持整数,因此只需将prog2 = prog/5更改为prog2 = int(prog/5))


以下是我的Python 3解决方案:

import time
for i in range(100):
    time.sleep(1)
    s = "{}% Complete".format(i)
    print(s,end=len(s) * '\b')

'\b'是反斜杠,对应字符串中的每个字符。 这在Windows cmd窗口内不起作用。


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

将以下内容添加到新文件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

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


Tqdm:在你的循环中添加一个进度表:

>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
...     time.sleep(1)
... 
|###-------| 35/100  35% [elapsed: 00:35 left: 01:05,  1.00 iters/sec]


它只有不到10行代码。

要点如下:https://gist.github.com/vladignatyev/06860ec2040cb497f0f3

import sys


def progress(count, total, suffix=''):
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', suffix))
    sys.stdout.flush()  # As suggested by Rom Ruben


import time,sys

for i in range(100+1):
    time.sleep(0.1)
    sys.stdout.write(('='*i)+(''*(100-i))+("\r [ %d"%i+"% ] "))
    sys.stdout.flush()

输出

[29 percent] ===================


试试由Python界的莫扎特Armin Ronacher编写的点击库。

$ pip install click # both 2 and 3 compatible

创建一个简单的进度条:

import click

with click.progressbar(range(1000000)) as bar:
    for i in bar:
        pass 

这是它的样子:

# [###-------------------------------]    9%  00:01:14

定制您心中的内容:

import click, sys

with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
    for i in bar:
        pass

自定义:

(_(_)===================================D(_(_| 100000/100000 00:00:02

还有更多的选项,请参阅API文档:

 click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)

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)

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()

我推荐使用tqdm - https://pypi.python.org/pypi/tqdm -它可以简单地将任何可迭代对象或进程转换为进度条,并处理所需终端的所有混乱。

从文档中可以看到:“tqdm可以很容易地支持回调/钩子和手动更新。这里有一个urllib的例子。”

import urllib
from tqdm import tqdm

def my_hook(t):
  """
  Wraps tqdm instance. Don't forget to close() or __exit__()
  the tqdm instance once you're done with it (easiest using `with` syntax).

  Example
  -------

  >>> with tqdm(...) as t:
  ...     reporthook = my_hook(t)
  ...     urllib.urlretrieve(..., reporthook=reporthook)

  """
  last_b = [0]

  def inner(b=1, bsize=1, tsize=None):
    """
    b  : int, optional
        Number of blocks just transferred [default: 1].
    bsize  : int, optional
        Size of each block (in tqdm units) [default: 1].
    tsize  : int, optional
        Total size (in tqdm units). If [default: None] remains unchanged.
    """
    if tsize is not None:
        t.total = tsize
    t.update((b - last_b[0]) * bsize)
    last_b[0] = b
  return inner

eg_link = 'http://www.doc.ic.ac.uk/~cod11/matryoshka.zip'
with tqdm(unit='B', unit_scale=True, miniters=1,
          desc=eg_link.split('/')[-1]) as t:  # all optional kwargs
    urllib.urlretrieve(eg_link, filename='/dev/null',
                       reporthook=my_hook(t), data=None)

函数从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()

python模块progressbar是一个不错的选择。 下面是我的典型代码:

import time
import progressbar

widgets = [
    ' ', progressbar.Percentage(),
    ' ', progressbar.SimpleProgress(format='(%(value_s)s of %(max_value_s)s)'),
    ' ', progressbar.Bar('>', fill='.'),
    ' ', progressbar.ETA(format_finished='- %(seconds)s  -', format='ETA: %(seconds)s', ),
    ' - ', progressbar.DynamicMessage('loss'),
    ' - ', progressbar.DynamicMessage('error'),
    '                          '
]

bar = progressbar.ProgressBar(redirect_stdout=True, widgets=widgets)
bar.start(100)
for i in range(100):
    time.sleep(0.1)
    bar.update(i + 1, loss=i / 100., error=i)
bar.finish()

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)):
...

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

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   ] 

把我在这里找到的一些想法放在一起,加上估计的剩余时间:

import datetime, sys

start = datetime.datetime.now()

def print_progress_bar (iteration, total):

    process_duration_samples = []
    average_samples = 5

    end = datetime.datetime.now()

    process_duration = end - start

    if len(process_duration_samples) == 0:
        process_duration_samples = [process_duration] * average_samples

    process_duration_samples = process_duration_samples[1:average_samples-1] + [process_duration]
    average_process_duration = sum(process_duration_samples, datetime.timedelta()) / len(process_duration_samples)
    remaining_steps = total - iteration
    remaining_time_estimation = remaining_steps * average_process_duration

    bars_string = int(float(iteration) / float(total) * 20.)
    sys.stdout.write(
        "\r[%-20s] %d%% (%s/%s) Estimated time left: %s" % (
            '='*bars_string, float(iteration) / float(total) * 100,
            iteration,
            total,
            remaining_time_estimation
        ) 
    )
    sys.stdout.flush()
    if iteration + 1 == total:
        print 


# Sample usage

for i in range(0,300):
    print_progress_bar(i, 300)

安装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]

对于python 3:

def progress_bar(current_value, total):
    increments = 50
    percentual = ((current_value/ total) * 100)
    i = int(percentual // (100 / increments ))
    text = "\r[{0: <{1}}] {2}%".format('=' * i, increments, percentual)
    print(text, end="\n" if percentual == 100 else "")

尝试安装这个包:pip install progressbar2:

import time
import progressbar

for i in progressbar.progressbar(range(100)):
    time.sleep(0.02)

进度栏 GitHub: https://github.com/WoLpH/python-progressbar


一个非常简单的解决方案是将以下代码放入循环中:

把这个放在你的文件的主体(即顶部):

import sys

把这个放在你的循环体中:

sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally