Python进度栏


307

当脚本执行可能需要花费时间的某些任务时,如何使用进度条?

例如,一个需要花费一些时间才能完成并True在完成后返回的函数。在执行功能期间如何显示进度条?

请注意,我需要做到这一点是实时的,所以我不知道该怎么做。我需要thread这个吗?我不知道。

现在,我在执行函数时不打印任何内容,但是进度条会很不错。另外,我对如何从代码角度完成此操作更感兴趣。


您仅使用GUI工具包还是CLI?
鲍比(Bobby)2010年

CLI。但是我可以使用第三方库,这没有问题。使用GUI可以做到这一点,但是我对CLI部分很感兴趣。
user225312

1
控制台中“ 文本进度栏”的可能重复项 注意,尽管此问题是三天前发布的,但链接的问题却被更频繁地查看。
Greenstick

这里是一个Jupyter笔记本内的解决方案:mikulskibartosz.name/...
史蒂芬C.霍维尔

我发布了一种新型的进度条,除了非常酷的动画外,您还可以打印,查看吞吐量和eta甚至暂停它!请看一下:github.com/rsalmei/alive-progress进行中
-rsalmei

Answers:


185

有特定的库(例如此处的库),但也许可以做一些简单的事情:

import time
import sys

toolbar_width = 40

# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['

for i in xrange(toolbar_width):
    time.sleep(0.1) # do real work here
    # update the bar
    sys.stdout.write("-")
    sys.stdout.flush()

sys.stdout.write("]\n") # this ends the progress bar

注:progressbar2是叉子进度尚未保持多年。


14
这并不能扩展很多步骤... pypi.python.org/pypi/progress易于使用
m13r 2015年

5
我尝试了这段代码,并引发了NameError: name 'xrange' is not defined错误。我是否缺少模块?
Mushroom Man

6
@ GokuMcSpock9733您正在使用哪个版本的Python?Python的2 xrange是Python的3 range
夸普卡

9
这不应该是最佳答案。至少对我来说,另一个答案(使用tqdm)要好得多。
Florian

1
Python 3中穷人的进度条print('■', end='', flush=True)
PatrickT

350

使用tqdm,您可以在一秒钟内将进度表添加到循环中:

In [1]: import time

In [2]: from tqdm import tqdm

In [3]: for i in tqdm(range(10)):
   ....:     time.sleep(3)

 60%|██████    | 6/10 [00:18<00:12,  0.33 it/s]

此外,由于v2.0.0d977a0c),因此还有tqdm的图形版本:

In [1]: import time

In [2]: from tqdm import tqdm_gui

In [3]: for i in tqdm_gui(range(100)):
  ....:     time.sleep(3)

tqdm gui窗口

但是要小心,因为tqdm_gui可以引发TqdmExperimentalWarning: GUI is experimental/alpha,您可以使用来忽略它warnings.simplefilter("ignore"),但是此后它将忽略代码中的所有警告。


9
这是我发现可用于终端机,qtconsole和笔记本电脑的唯一解决方案
Ivelin

3
它可以迭代吗?我很难让它与字符串列表一起使用。
乔什·乌斯雷

3
@JoshUsre是的,它应该与任何可迭代项一起使用,目前我还没有看到任何可迭代项。但是,ETA(剩余时间)的显示要求迭代器具有__len__属性,否则用户必须将total参数提供给tqdm。否则,该酒吧将运作,但没有ETA。
令人赞叹的

6
@gaborous:为什么这不是最受好评的答案?与简单的解决方案不同,此简单的解决方案在终端和Jupyter笔记本电脑中均有效。
EBE艾萨克

6
适用于在jupyter笔记本中运行from tqdm import tqdm_notebook as tqdm。否则不要将其写在一行上。
雅克·马拉帕德

81

上面的建议是相当不错的,但是我认为大多数人只想要一个现成的解决方案,不依赖于外部软件包,而是可以重用的。

我获得了以上所有方面的优点,并将其与测试用例一起成为一个函数。

要使用它,只需复制“ def update_progress(progress)”下的行,而不复制测试脚本。不要忘记导入sys。每当您需要显示或更新进度条时,请调用此函数。

通过直接将“ \ r”符号发送到控制台以将光标移回开始位置来工作。python中的“ print”不能将上面的符号用于此目的,因此我们需要'sys'

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


# update_progress test script
print "progress : 'hello'"
update_progress("hello")
time.sleep(1)

print "progress : 3"
update_progress(3)
time.sleep(1)

print "progress : [23]"
update_progress([23])
time.sleep(1)

print ""
print "progress : -10"
update_progress(-10)
time.sleep(2)

print ""
print "progress : 10"
update_progress(10)
time.sleep(2)

print ""
print "progress : 0->1"
for i in range(101):
    time.sleep(0.1)
    update_progress(i/100.0)

print ""
print "Test completed"
time.sleep(10)

这是测试脚本的结果显示的内容(最后一个进度条动画):

progress : 'hello'
Percent: [----------] 0% error: progress var must be float
progress : 3
Percent: [##########] 100% Done...
progress : [23]
Percent: [----------] 0% error: progress var must be float

progress : -10
Percent: [----------] 0% Halt...

progress : 10
Percent: [##########] 100% Done...

progress : 0->1
Percent: [##########] 100% Done...
Test completed

10
动画测试(最后一个测试)应该说in range(101)不是100,进度停止在99%,并且永远不会显示完成。
Nick Humrich 2014年

40

这个答案不依赖于外部软件包,我还认为大多数人只想要现成的代码。通过自定义,可以使以下代码适合您的需求:进度'#'size,进度条,文本prefix等。

import sys

def progressbar(it, prefix="", size=60, file=sys.stdout):
    count = len(it)
    def show(j):
        x = int(size*j/count)
        file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
        file.flush()        
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    file.write("\n")
    file.flush()

用法:

import time

for i in progressbar(range(15), "Computing: ", 40):
    time.sleep(0.1) # any calculation you need

输出:

Computing: [################........................] 4/15
  • 不需要第二个线程。上面的某些解决方案/软件包需要。例如,第二个线程可能是个问题jupyter notebook

  • 与任何可迭代的作品一起工作意味着len()可以使用的任何东西。A listdict例如a['a', 'b', 'c' ... 'g']

您还可以通过将文件更改sys.stderr为例如来更改输出


我喜欢这种解决方案,生成器将引发以下错误:TypeError: object of type 'generator' has no len()
jabellcu

在这种情况下,@jabellcu(generators)必须用来包装list()。喜欢for i in progressbar(list(your_generator), "Computing: ", 40):
eusoubrasileiro

22

对于类似的应用程序(跟踪循环中的进度),我只使用了python-progressbar

他们的榜样是这样的,

from progressbar import *               # just a simple progress bar


widgets = ['Test: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),
           ' ', ETA(), ' ', FileTransferSpeed()] #see docs for other options

pbar = ProgressBar(widgets=widgets, maxval=500)
pbar.start()

for i in range(100,500+1,50):
    # here do something long at each iteration
    pbar.update(i) #this adds a little symbol at each iteration
pbar.finish()
print

3
为了与Python 3兼容,请尝试progressbar2打包。上面的代码可以使用它。
d33tah

2
您真的使用过import *吗?
eric

20

https://pypi.python.org/pypi/progress尝试进度。

from progress.bar import Bar

bar = Bar('Processing', max=20)
for i in range(20):
    # Do some work
    bar.next()
bar.finish()

结果将是如下所示的条形:

Processing |#############                   | 42/100

刚试过这个。非常容易使用。我花了2分钟(包括pip安装进度)花了我一个时间来启动并运行状态栏。
perelin

progress效果不错,但如果使用其他软件则失败stderr。抱歉,但我尚未调查确切的问题。
亚瑟

它在我的ubuntu控制台中为每个进度打印一行,例如,如果max = 20,它将打印20行...如何使它仅打印一行?
L的世界

19

在这里搜索等效解决方案后,我根据自己的需求做了一个简单的进度课程。我以为我可能会发布它。

from __future__ import print_function
import sys
import re


class ProgressBar(object):
    DEFAULT = 'Progress: %(bar)s %(percent)3d%%'
    FULL = '%(bar)s %(current)d/%(total)d (%(percent)3d%%) %(remaining)d to go'

    def __init__(self, total, width=40, fmt=DEFAULT, symbol='=',
                 output=sys.stderr):
        assert len(symbol) == 1

        self.total = total
        self.width = width
        self.symbol = symbol
        self.output = output
        self.fmt = re.sub(r'(?P<name>%\(.+?\))d',
            r'\g<name>%dd' % len(str(total)), fmt)

        self.current = 0

    def __call__(self):
        percent = self.current / float(self.total)
        size = int(self.width * percent)
        remaining = self.total - self.current
        bar = '[' + self.symbol * size + ' ' * (self.width - size) + ']'

        args = {
            'total': self.total,
            'bar': bar,
            'current': self.current,
            'percent': percent * 100,
            'remaining': remaining
        }
        print('\r' + self.fmt % args, file=self.output, end='')

    def done(self):
        self.current = self.total
        self()
        print('', file=self.output)

范例:

from time import sleep

progress = ProgressBar(80, fmt=ProgressBar.FULL)

for x in xrange(progress.total):
    progress.current += 1
    progress()
    sleep(0.1)
progress.done()

将打印以下内容:

[======== ] 17/80 ( 21%) 63 to go


3
太好了,谢谢你。顺便说一句,您可以progress.current在末尾添加增量,__call__以进一步限制与主代码中对象的交互。
npit

这段代码简单,简洁,有用!谢谢!
伊恩·瑞温克尔

15

我喜欢Brian Khuu的回答,因为它简单易用,不需要外部软件包。我做了一些更改,所以我在这里添加了我的版本:

import sys
import time


def updt(total, progress):
    """
    Displays or updates a console progress bar.

    Original source: https://stackoverflow.com/a/15860757/1391441
    """
    barLength, status = 20, ""
    progress = float(progress) / float(total)
    if progress >= 1.:
        progress, status = 1, "\r\n"
    block = int(round(barLength * progress))
    text = "\r[{}] {:.0f}% {}".format(
        "#" * block + "-" * (barLength - block), round(progress * 100, 0),
        status)
    sys.stdout.write(text)
    sys.stdout.flush()


runs = 300
for run_num in range(runs):
    time.sleep(.1)
    updt(runs, run_num + 1)

假设total运行总次数()和到目前为止已处理的运行次数(progresstotal >= progress。结果看起来像这样:

[#####---------------] 27%

14

您可以使用tqdm

from tqdm import tqdm

with tqdm(total=100, desc="Adding Users", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
    for i in range(100):
        time.sleep(3)
        pbar.update(1)

在此示例中,进度条运行5分钟,如下所示:

Adding Users:   3%|█████▊                                     [ time left: 04:51 ]                                                                                                        

您可以根据需要对其进行更改和自定义。


11

为了以一种有用的方式使用任何进度条框架,即获得实际进度百分比和估计的ETA,您需要能够声明将要执行的步骤数。

因此,您的计算功能位于另一个线程中,是否可以将其拆分为多个逻辑步骤?您可以修改其代码吗?

您不需要重构它或将其拆分为实际方法,您只需yield在其中的某些位置添加一些策略性的!如果昂贵的函数具有for循环,则只需在其中放入一个。最后,您应该只知道要完成多少产量才能获得最佳结果。

这样,您的函数可能是这样的:

def compute():
    time.sleep(1)  # some processing here
    yield  # insert these
    time.sleep(1)
    yield
    time.sleep(1)
    yield

或这个:

def compute():
    for i in range(1000):
        time.sleep(.1)  # some processing here
        yield  # insert these

使用这种功能,您可以安装:

pip install alive-progress

并像这样使用它:

from alive_progress import alive_bar

with alive_bar(3) as bar:  # or a 1000 in the loop example.
    for i in compute():
        bar()

要获得一个很棒的进度条!

|█████████████▎                          | ▅▃▁ 1/3 [33%] in 1s (1.0/s, eta: 2s)

免责声明:我是alive_progress的作者,但它应该可以很好地解决您的问题。阅读位于的文档 https://github.com/rsalmei/alive-progress,这是它可以做什么的示例:

活着的进步


8

我真的很喜欢python-progressbar,因为它非常易于使用。

对于最简单的情况,它只是:

import progressbar
import time

progress = progressbar.ProgressBar()
for i in progress(range(80)):
    time.sleep(0.01)

外观可以自定义,并且可以显示估计的剩余时间。例如,使用与上面相同的代码,但是:

progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',
                                            progressbar.Percentage(), ' ',
                                            progressbar.ETA()])

5

如果这是一个循环且迭代次数固定的循环,需要花费大量时间,则可以使用我制作的此函数。循环的每次迭代都会增加进度。其中count是循环的当前迭代,total是您要循环到的值,size(int)是您希望条以10为增量的大小,即(大小1 = 10个字符,大小2 = 20个字符)

import sys
def loadingBar(count,total,size):
    percent = float(count)/float(total)*100
    sys.stdout.write("\r" + str(int(count)).rjust(3,'0')+"/"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']')

例:

for i in range(0,100):
     loadingBar(i,100,2)
     #do some code 

输出:

i = 50
>> 050/100 [==========          ]


4

下面的代码是一个非常通用的解决方案,并且具有经过的时间和剩余时间估算。您可以使用任何可迭代的方法。进度条的大小固定为25个字符,但可以使用完整,一半和四分之一字符以1%的步长显示更新。输出如下所示:

 18% |████▌                    | \ [0:00:01, 0:00:06]

带有示例的代码:

import sys, time
from numpy import linspace

def ProgressBar(iterObj):
  def SecToStr(sec):
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    return u'%d:%02d:%02d'%(h, m, s)
  L = len(iterObj)
  steps = {int(x):y for x,y in zip(linspace(0, L, min(100,L), endpoint=False),
                                   linspace(0, 100, min(100,L), endpoint=False))}
  qSteps = ['', u'\u258E', u'\u258C', u'\u258A'] # quarter and half block chars
  startT = time.time()
  timeStr = '   [0:00:00, -:--:--]'
  activity = [' -',' \\',' |',' /']
  for nn,item in enumerate(iterObj):
    if nn in steps:
      done = u'\u2588'*int(steps[nn]/4.0)+qSteps[int(steps[nn]%4)]
      todo = ' '*(25-len(done))
      barStr = u'%4d%% |%s%s|'%(steps[nn], done, todo)
    if nn>0:
      endT = time.time()
      timeStr = ' [%s, %s]'%(SecToStr(endT-startT),
                             SecToStr((endT-startT)*(L/float(nn)-1)))
    sys.stdout.write('\r'+barStr+activity[nn%4]+timeStr); sys.stdout.flush()
    yield item
  barStr = u'%4d%% |%s|'%(100, u'\u2588'*25)
  timeStr = '   [%s, 0:00:00]\n'%(SecToStr(time.time()-startT))
  sys.stdout.write('\r'+barStr+timeStr); sys.stdout.flush()

# Example
s = ''
for c in ProgressBar(list('Disassemble and reassemble this string')):
  time.sleep(0.2)
  s += c
print(s)

对于改进的建议或其他评论表示赞赏。干杯!


3

我喜欢这个页面

从简单的示例开始,然后转到多线程版本。开箱即用。无需第三方套餐。

该代码将如下所示:

import time
import sys

def do_task():
    time.sleep(1)

def example_1(n):
    for i in range(n):
        do_task()
        print '\b.',
        sys.stdout.flush()
    print ' Done!'

print 'Starting ',
example_1(10)

或者下面是使用线程以便在程序运行时运行旋转加载栏的示例:

import sys
import time
import threading

class progress_bar_loading(threading.Thread):

    def run(self):
            global stop
            global kill
            print 'Loading....  ',
            sys.stdout.flush()
            i = 0
            while stop != True:
                    if (i%4) == 0: 
                        sys.stdout.write('\b/')
                    elif (i%4) == 1: 
                        sys.stdout.write('\b-')
                    elif (i%4) == 2: 
                        sys.stdout.write('\b\\')
                    elif (i%4) == 3: 
                        sys.stdout.write('\b|')

                    sys.stdout.flush()
                    time.sleep(0.2)
                    i+=1

            if kill == True: 
                print '\b\b\b\b ABORT!',
            else: 
                print '\b\b done!',


kill = False      
stop = False
p = progress_bar_loading()
p.start()

try:
    #anything you want to run. 
    time.sleep(1)
    stop = True
except KeyboardInterrupt or EOFError:
         kill = True
         stop = True

3

在Python3中非常简单:

   import time
   import math

    def show_progress_bar(bar_length, completed, total):
        bar_length_unit_value = (total / bar_length)
        completed_bar_part = math.ceil(completed / bar_length_unit_value)
        progress = "*" * completed_bar_part
        remaining = " " * (bar_length - completed_bar_part)
        percent_done = "%.2f" % ((completed / total) * 100)
        print(f'[{progress}{remaining}] {percent_done}%', end='\r')

    bar_length = 30
    total = 100
    for i in range(0, total + 1):
        show_progress_bar(bar_length, i, total)
        time.sleep(0.1)

    print('\n')

3

在Jupyter笔记本电脑中运行时,无法正常使用tqdm,因为它会在多行上写入输出。使用此代替:

import time
from tqdm import tqdm_notebook as tqdm

for i in tqdm(range(100))
    time.sleep(0.5)

2

如果您的工作无法分解为可测量的块,则可以在新线程中调用函数并花费多长时间:

import thread
import time
import sys

def work():
    time.sleep( 5 )

def locked_call( func, lock ):
    lock.acquire()
    func()
    lock.release()

lock = thread.allocate_lock()
thread.start_new_thread( locked_call, ( work, lock, ) )

# This part is icky...
while( not lock.locked() ):
    time.sleep( 0.1 )

while( lock.locked() ):
    sys.stdout.write( "*" )
    sys.stdout.flush()
    time.sleep( 1 )
print "\nWork Done"

您显然可以根据需要提高计时精度。


答案中的代码将在哪里测量?
unseen_rider

2

我喜欢Gabriel的答案,但我将其更改为灵活的。您可以将bar长度发送到函数,并获得所需长度的进度条。而且,进度条的长度不能为零或为负。另外,您可以像Gabriel答案一样使用此功能(请参见示例2)。

import sys
import time

def ProgressBar(Total, Progress, BarLength=20, ProgressIcon="#", BarIcon="-"):
    try:
        # You can't have a progress bar with zero or negative length.
        if BarLength <1:
            BarLength = 20
        # Use status variable for going to the next line after progress completion.
        Status = ""
        # Calcuting progress between 0 and 1 for percentage.
        Progress = float(Progress) / float(Total)
        # Doing this conditions at final progressing.
        if Progress >= 1.:
            Progress = 1
            Status = "\r\n"    # Going to the next line
        # Calculating how many places should be filled
        Block = int(round(BarLength * Progress))
        # Show this
        Bar = "[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(Progress * 100, 0), Status)
        return Bar
    except:
        return "ERROR"

def ShowBar(Bar):
    sys.stdout.write(Bar)
    sys.stdout.flush()

if __name__ == '__main__':
    print("This is a simple progress bar.\n")

    # Example #1:
    print('Example #1')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, Runs)
        ShowBar(progressBar)
        time.sleep(1)

    # Example #2:
    print('\nExample #2')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, 20, '|', '.')
        ShowBar(progressBar)
        time.sleep(1)

    print('\nDone.')

# Example #2:
Runs = 10
for i in range(Runs + 1):
    ProgressBar(10, i)
    time.sleep(1)

结果:

这是一个简单的进度栏。

例子1

进度:[### -------] 30%

范例#2

进度:[|||||||||||| ........] 60%

做完了


2

我用format()方法制作了一个负载条。这是我的解决方案:

import time

loadbarwidth = 23

for i in range(1, loadbarwidth + 1):
    time.sleep(0.1) 

    strbarwidth = '[{}{}] - {}\r'.format(
        (i * '#'),
        ((loadbarwidth - i) * '-'),
        (('{:0.2f}'.format(((i) * (100/loadbarwidth))) + '%'))
    )

    print(strbarwidth ,end = '')

print()

输出:

[#######################] - 100.00%

1

这是一个简短的解决方案,可以以编程方式构建加载栏(您必须确定所需的时间)。

import time

n = 33  # or however many loading slots you want to have
load = 0.01  # artificial loading time!
loading = '.' * n  # for strings, * is the repeat operator

for i in range(n+1):
    # this loop replaces each dot with a hash!
    print('\r%s Loading at %3d percent!' % (loading, i*100/n), end='')
    loading = loading[:i] + '#' + loading[i+1:]
    time.sleep(load)

1

尝试PyProg。PyProg是Python的开放源代码库,用于创建超级可自定义的进度指示器和栏。

当前版本为1.0.2;它托管在Github上,可在PyPI上使用(下面的链接)。它与Python 3&2兼容,也可以与Qt Console一起使用。

真的很容易使用。如下代码:

import pyprog
from time import sleep

# Create Object
prog = pyprog.ProgressBar(" ", "", 34)
# Update Progress Bar
prog.update()

for i in range(34):
    # Do something
    sleep(0.1)
    # Set current status
    prog.set_stat(i + 1)
    # Update Progress Bar again
    prog.update()

# Make the Progress Bar final
prog.end()

将产生:

Initial State:
Progress: 0% --------------------------------------------------

When half done:
Progress: 50% #########################-------------------------

Final State:
Progress: 100% ##################################################

我之所以制作PyProg是因为我需要一个简单但可自定义的进度条库。您可以使用轻松地安装它pip install pyprog

PyProg Github:https : //github.com/Bill13579/pyprog
PyPI:https ://pypi.python.org/pypi/pyprog/


1

您也可以使用enlighten。主要优点是您可以同时登录,而不会覆盖进度条。

import time
import enlighten

manager = enlighten.Manager()
pbar = manager.counter(total=100)

for num in range(1, 101):
    time.sleep(0.05)
    print('Step %d complete' % num)
    pbar.update()

它还处理多个进度条。

import time
import enlighten

manager = enlighten.Manager()
odds = manager.counter(total=50)
evens = manager.counter(total=50)

for num in range(1, 101):
    time.sleep(0.05)
    if num % 2:
        odds.update()
    else:
        evens.update()

1

使用进度库

pip install progress

这是我编写的一个自定义子类,用于将ETA /经过时间格式化为更好的可读格式:

import datetime
from progress.bar import IncrementalBar


class ProgressBar(IncrementalBar):
    '''
    My custom progress bar that:
       - Show %, count, elapsed, eta
       - Time is shown in H:M:S format
    '''

    message = 'Progress'
    suffix  = '%(percent).1f%% (%(index)d/%(max)d) -- %(elapsed_min)s (eta: %(eta_min)s)'

    def formatTime(self, seconds):
        return str(datetime.timedelta(seconds=seconds))

    @property
    def elapsed_min(self):
        return self.formatTime(self.elapsed)

    @property
    def eta_min(self):
        return self.formatTime(self.eta)

if __name__=='__main__':
    counter = 120
    bar     = ProgressBar('Processing', max=counter)

    for i in range(counter):
        bar.next()
        time.sleep(1)

    bar.finish()

1

这是我的简单解决方案:

import time

def progress(_cur, _max):
    p = round(100*_cur/_max)
    b = f"Progress: {p}% - ["+"."*int(p/5)+" "*(20-int(p/5))+"]"
    print(b, end="\r")

# USAGE:
for i in range(0,101):
    time.sleep(0.1) 
    progress(i,100)

print("..."*5, end="\r")
print("Done")

0

您应该将进度条链接到手头的任务(以便它衡量进度:D)。例如,如果您正在通过FTP传输文件,则可以告诉ftplib抓取一定大小的缓冲区,比方说128K,然后将128k代表的文件大小的任何百分比添加到进度栏中。如果您使用的是CLI,并且进度条的长度为20个字符,则在文件的1/20传输完后,您将添加一个字符。


就我而言,我使用的是API,它不提供获取特定块的功能。谢谢你的主意,这很好。
user225312

0

@Massagran:它在我的程序中效果很好。此外,我们需要添加一个计数器来指示循环时间。此计数器用作方法的参数update。例如:读取测试文件的所有行并将它们放在某些东西上。假设函数dosth()与变量无关i

lines = open(sys.argv[1]).readlines()
i = 0
widgets=[Percentage(), Bar()]
pbar = ProgressBar(widgets=widgets,maxval=len(lines)).start()
pbar.start()
for line in lines:<pre>
    dosth();
    i += 1
    pbar.update(i)</pre>
pbar.finish()

变量通过方法i控制状态pbarupdate


0

jelde015的通用答案(当然要归功于他)

手动更新加载栏的方法是:

import sys
from math import *


def loadingBar(i, N, size):
    percent = float(i) / float(N)
    sys.stdout.write("\r"
                     + str(int(i)).rjust(3, '0')
                     +"/"
                     +str(int(N)).rjust(3, '0')
                     + ' ['
                     + '='*ceil(percent*size)
                     + ' '*floor((1-percent)*size)
                     + ']')

并通过以下方式调用:

loadingBar(7, 220, 40)

将导致:

007/220 [=                                       ]  

随时随地调用它即可 i值。

size条形图设置为字符数


0

猜猜我有点晚了,但这对使用当前版本python 3的人应该有用,因为它使用了 “ f-strings”,如Python 3.6 PEP 498中所介绍:

from numpy import interp

class Progress:
    def __init__(self, value, end, title='Downloading',buffer=20):
        self.title = title
        #when calling in a for loop it doesn't include the last number
        self.end = end -1
        self.buffer = buffer
        self.value = value
        self.progress()

    def progress(self):
        maped = int(interp(self.value, [0, self.end], [0, self.buffer]))
        print(f'{self.title}: [{"#"*maped}{"-"*(self.buffer - maped)}]{self.value}/{self.end} {((self.value/self.end)*100):.2f}%', end='\r')

#some loop that does perfroms a task
for x in range(21)  #set to 21 to include until 20
    Progress(x, 21)

输出量

Downloading: [########------------] 8/20 40.00%

0

这是创建进度条的简单方法

import time,sys
toolbar_width = 50
# setting up toolbar [-------------------------------------]
sys.stdout.write("[%s]"%(("-")*toolbar_width))
sys.stdout.flush()
# each hash represents 2 % of the progress
for i in range(toolbar_width):
    sys.stdout.write("\r") # return to start of line
    sys.stdout.flush()
    sys.stdout.write("[")#Overwrite over the existing text from the start 
    sys.stdout.write("#"*(i+1))# number of # denotes the progress completed 
    sys.stdout.flush()
    time.sleep(0.1)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.