代码之家  ›  专栏  ›  技术社区  ›  bobber205

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

  •  331
  • bobber205  · 技术社区  · 15 年前

    有没有一个好的方法来做下面的工作?

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

    每次下载一些数据块时,我都要更新一个文本进度条,即使它只是一个数字。

    但我不想删除所有打印到控制台的文本。(执行“清除”,然后打印更新的百分比。)

    31 回复  |  直到 6 年前
        1
  •  287
  •   Cris Luengo    6 年前

    下面是我经常使用的许多答案的汇总。

    # Print iterations progress
    def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
        """
        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)
        """
        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 = '\r')
        # Print New Line on Complete
        if iteration == total: 
            print()
    

    样品使用情况:

    from time import sleep
    
    # 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...
        sleep(0.1)
        # Update Progress Bar
        printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
    

    样品输出:

    Progress: |█████████████████████████████████████████████-----| 90.0% Complete
    
        2
  •  289
  •   Martin Thoma    10 年前

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

    显示百分比计数器:

    import time
    import sys
    
    for i in range(100):
        time.sleep(1)
        sys.stdout.write("\r%d%%" % i)
        sys.stdout.flush()
    
        4
  •  107
  •   aviraldg Ortiga    15 年前

    写一篇 \r 到控制台。那是一个 "carriage return" 这会导致所有文本在行首处被回送。类似:

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

    这会给你一些东西,比如: [ ########## ] 100%

        5
  •  61
  •   idmean    8 年前

    它少于10行代码。

    此处的要点: https://gist.github.com/vladignayev/06860ec2040cb49f0f3f3

    导入系统 def progress(count,total,suffix=''): 巴里伦=60 填充的_len=int(圆形(bar_len*计数/浮动(总计))) 百分比=整数(100.0*计数/浮点数(总计),1) bar='='*填充的_len+'-'*(bar_len-填充的_len) sys.stdout.write('[%s]%s%s…%s\r'%(bar,percents,'%,suffix)) 按rom ruben建议的sys.stdout.flush() < /代码>

    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
    

    enter image description here

        6
  •  52
  •   The Unfun Cat    10 年前

    试试 click 图书馆由巨蟒莫扎特,阿敏·罗纳赫所著。

    $ 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 docs :

     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)
    
        7
  •  30
  •   JoeLinux    12 年前

    我知道我迟到了,但这是我写的一个稍微有点雅致的风格(红帽子)(这里不是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%
    

    …支架保持静止,只有散列数增加。

    作为一名装饰师,这可能会更好。再过一天…

        8
  •  17
  •   scripts    13 年前

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

    link 提供其功能的快速概述

        9
  •  12
  •   Wolph    10 年前

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

    但如果你想自己写的话。你可以用 curses 使事情更容易的模块:)

    [编辑] 也许更容易的不是诅咒这个词。但如果你想创造一个全面的崔比诅咒照顾你很多东西。

    [编辑] 既然旧链接已经死了,我已经建立了自己版本的python progressbar,请点击这里: https://github.com/WoLpH/python-progressbar

        10
  •  10
  •   HibernatedGuy    10 年前
    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%]

        11
  •  7
  •   FraggaMuffin Verma    9 年前

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

    import sys
    
    class ProgressBar(object):
        DEFAULT_BAR_LENGTH = 65
        DEFAULT_CHAR_ON  = '='
        DEFAULT_CHAR_OFF = ' '
    
        def __init__(self, end, start=0):
            self.end    = end
            self.start  = start
            self._barLength = self.__class__.DEFAULT_BAR_LENGTH
    
            self.setLevel(self.start)
            self._plotted = False
    
        def setLevel(self, level):
            self._level = level
            if level < self.start:  self._level = self.start
            if level > self.end:    self._level = self.end
    
            self._ratio = float(self._level - self.start) / float(self.end - self.start)
            self._levelChars = int(self._ratio * self._barLength)
    
        def plotProgress(self):
            sys.stdout.write("\r  %3i%% [%s%s]" %(
                int(self._ratio * 100.0),
                self.__class__.DEFAULT_CHAR_ON  * int(self._levelChars),
                self.__class__.DEFAULT_CHAR_OFF * int(self._barLength - self._levelChars),
            ))
            sys.stdout.flush()
            self._plotted = True
    
        def setAndPlot(self, level):
            oldChars = self._levelChars
            self.setLevel(level)
            if (not self._plotted) or (oldChars != self._levelChars):
                self.plotProgress()
    
        def __add__(self, other):
            assert type(other) in [float, int], "can only add a number"
            self.setAndPlot(self._level + other)
            return self
        def __sub__(self, other):
            return self.__add__(-other)
        def __iadd__(self, other):
            return self.__add__(other)
        def __isub__(self, other):
            return self.__add__(-other)
    
        def __del__(self):
            sys.stdout.write("\n")
    
    if __name__ == "__main__":
        import time
        count = 150
        print "starting things:"
    
        pb = ProgressBar(count)
    
        #pb.plotProgress()
        for i in range(0, count):
            pb += 1
            #pb.setAndPlot(i + 1)
            time.sleep(0.01)
        del pb
    
        print "done"
    

    结果:

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

    这通常被认为是“超高层”,但当你经常使用它时,它是很方便的。

        12
  •  6
  •   PaulMcG    15 年前

    运行此 在python命令行 ( 在任何IDE或开发环境中):

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

    在我的Windows系统上工作正常。

        13
  •  6
  •   Tux    7 年前

    安装 tqdm .( pip install 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]
    
        15
  •  4
  •   Ib33X    9 年前

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

    编辑:固定链接

        16
  •  3
  •   Community CDub    8 年前

    基于上面的答案和其他类似的关于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%

        17
  •  3
  •   Malcolm Box    8 年前

    我建议使用TQDM- https://pypi.python.org/pypi/tqdm -这使得把任何一个不可测的或进程变成一个进度条变得简单,并处理所有与所需终端有关的问题。

    来自文档:“TQDM可以轻松支持回调/钩子和手动更新。这里是一个带urlib的例子”

    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)
    
        18
  •  3
  •   Chris Cui    7 年前

    尝试安装此程序包: pip install progressbar2 :

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

    进度BAR Github: https://github.com/WoLpH/python-progressbar

        19
  •  2
  •   Ramchandra Apte    12 年前
    import sys
    def progresssbar():
             for i in range(100):
                time.sleep(1)
                sys.stdout.write("%i\r" % i)
    
    progressbar()
    

    注意:如果您在Interactive Interest中运行此程序,则会打印出额外的数字。

        20
  •  2
  •   ryan    12 年前

    哈哈,我刚刚写了一整本书 这里的代码请记住,在执行块ASCII时不能使用Unicode,我使用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
    |█████     |
    
        21
  •  2
  •   Storm-Eyes    12 年前

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

    不过,我想指出一些缺点

    1. 每次刷新进度条时,它都将在新行上开始。

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

      这样地:
      [] 0%
      [S](10%)
      [Sux](20%)
      [S1(30%)]

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

    下面的代码将解决上述问题。

    def update_progress(progress, total):  
        print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
    
        22
  •  2
  •   Richard Hayman-Joyce    7 年前

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

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

    import sys
    

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

    sys.stdout.write("-") # prints a dash for each iteration of loop
    sys.stdout.flush() # ensures bar is displayed incrementally
    
        23
  •  1
  •   Ilia w495 Nikitin emd_22    8 年前

    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()
    
        24
  •  1
  •   Ivan Chaer    7 年前

    把我在这里发现的一些想法放在一起,并增加估计剩余时间:

    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)
    
        25
  •  0
  •   Cold Diamondz    12 年前

    好吧,这里有一些代码可以工作,我在发布之前测试了它:

    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) )
        26
  •  0
  •   Matt-the-Bat    11 年前

    下面是我的python 3解决方案:

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

    “\b”是一个反斜杠,用于字符串中的每个字符。 这在Windows命令窗口中不起作用。

        27
  •  0
  •   Edmond de Martimprey    8 年前

    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()
    
        28
  •  0
  •   Aimin Huang    8 年前

    python模块 控件 是个不错的选择。 这是我的典型代码:

    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()
    
        29
  •  0
  •   Antoine Boucher    8 年前

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

    进展BAR2 对于命令行的ascii基progressbar是一个很好的库 导入时间 导入进度条

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

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

    全面质量管理 是progressbar2的替代品,我认为它在pip3中使用,但我不确定

    from tqdm import tqdm
    for i in tqdm(range(10000)):
    ...
    
        30
  •  0
  •   jenkins    8 年前

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

    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%(oncmp)条形图中的文本和边框。

    这里有一个例子:

    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% [######              ]
    

    完成时输出:

    100% [   done in 9 sec   ]