简体   繁体   English

Python 进度条

[英]Python Progress Bar

How do I use a progress bar when my script is doing some task that is likely to take time?当我的脚本正在执行一些可能需要时间的任务时,如何使用进度条?

For example, a function which takes some time to complete and returns True when done.例如,一个 function 需要一些时间才能完成并在完成时返回True How can I display a progress bar during the time the function is being executed?如何在执行 function 期间显示进度条?

Note that I need this to be in real time, so I can't figure out what to do about it.请注意,我需要它是实时的,所以我不知道该怎么做。 Do I need a thread for this?我需要一个thread吗? I have no idea.我不知道。

Right now I am not printing anything while the function is being executed, however a progress bar would be nice.现在在执行 function 时我没有打印任何东西,但是进度条会很好。 Also I am more interested in how this can be done from a code point of view.此外,我对如何从代码的角度完成此操作更感兴趣。

With tqdm ( conda install tqdm or pip install tqdm ) you can add a progress meter to your loops in a second:使用tqdm ( conda install tqdmpip install tqdm ),您可以在一秒钟内将进度表添加到您的循环中:

from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
    sleep(3)

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

Also, there is a notebook version :此外,还有一个笔记本版本

from tqdm.notebook import tqdm
for i in tqdm(range(100)):
    sleep(3)

You can use tqdm.auto instead of tqdm.notebook to work in both a terminal and notebooks.您可以使用tqdm.auto而不是tqdm.notebook在终端和笔记本中工作。

tqdm.contrib contains some helper functions to do things like enumerate , map , and zip . tqdm.contrib包含一些辅助函数来执行诸如enumeratemapzip之类的操作。 There are concurrent maps in tqdm.contrib.concurrent . tqdm.contrib.concurrent中有并发映射。

You can even get progress sent to your phone after disconnecting from a jupyter notebook using tqdm.contrib.telegram or tqdm.contrib.discord .使用tqdm.contrib.telegramtqdm.contrib.discord断开与 jupyter notebook 的连接后,您甚至可以将进度发送到您的手机。

GIF 显示使用 tqdm.contrib.telegram 在 Telegram 移动应用程序中显示进度条的输出示例

There are specific libraries ( like this one here ) but maybe something very simple would do:有特定的库(比如这里的这个),但也许可以做一些非常简单的事情:

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

Note: progressbar2 is a fork of progressbar which hasn't been maintained in years.注意: progressbar2是一个多年未维护的进度条的分支。

Use alive-progress , the coolest progress bar ever!使用alive-progress ,有史以来最酷的进度条!

GIF 显示了一个活着的进步的例子

To use any progress bar framework in a useful manner, ie to get a percentage of completion and an estimated time of arrival (ETA), you need to be able to tell how many steps your processing will have.要以有用的方式使用任何进度条框架,即获得完成百分比和预计到达时间 (ETA),您需要能够知道您的处理将有多少个步骤。

Then you can just insert an yield to mark an item has been processed, and you're good to go!然后你可以插入一个yield来标记一个项目已被处理,你就可以开始了!

def compute():
    for i in range(1000):
        ... # process items as usual.
        yield  # insert this :)

Then just use it like:然后像这样使用它:

from alive_progress import alive_bar

with alive_bar(1000) as bar:
    for i in compute():
        bar()

To get an awesome and alive progress bar!获得一个真棒和生动的进度条!

|█████████████▎                      | ▅▃▁ 321/1000 [32%] in 8s (40.1/s, eta: 16s)

Disclosure: I'm the author of alive-progress , but it should solve your problem nicely!披露:我是alive-progress的作者,但它应该可以很好地解决您的问题! Read the documentation at https://github.com/rsalmei/alive-progress to know more.阅读https://github.com/rsalmei/alive-progress上的文档以了解更多信息。 Now it works also on Jupyter Notebooks!现在它也适用于 Jupyter Notebooks! Here are some more examples of what it can do:以下是它可以做什么的更多示例:

GIF 显示各种风格的生活进度

GIF 显示 Jupyter Notebooks 上的实时进度

No external packages.没有外部软件包。 A ready-made piece of code.一段现成的代码。

You can customize bar progress symbol "#" , bar size , text prefix etc.您可以自定义栏进度符号"#" 、栏size 、文本prefix等。

Python 3.3+ Python 3.3+

import sys
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.3+
    count = len(it)
    def show(j):
        x = int(size*j/count)
        print("{}[{}{}] {}/{}".format(prefix, "#"*x, "."*(size-x), j, count), 
                end='\r', file=out, flush=True)
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    print("\n", flush=True, file=out)

Usage:用法:

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

To fill the whole character space use a unicode u"█" char replacing "#" .要填充整个字符空间,请使用 unicode u"█" char 替换"#" With for i in progressbar(range(100)): ... you get :随着for i in progressbar(range(100)): ...你得到:

在此处输入图像描述

  • Doesn't require a second thread .不需要第二个线程 Some solutions/packages above require.上面的一些解决方案/包需要。

  • Works with any iterable it means anything that len() can be used on.适用于任何可迭代对象,这意味着可以使用len()的任何对象。 A list , a dict of anything for example ['a', 'b', 'c' ... 'g']一个list ,任何东西的dict ,例如['a', 'b', 'c' ... 'g']

  • Works with generators only have to wrap it with a list().与生成器一起工作只需要用 list() 包装它。 For example for i in progressbar(list(your_generator), "Computing: ", 40): Unless the work is done in the generator.例如for i in progressbar(list(your_generator), "Computing: ", 40):除非工作是在生成器中完成的。 In that case you need another solution (like tqdm) .在这种情况下,您需要另一种解决方案(如 tqdm)

You can also change output by changing out to sys.stderr for example.例如,您还可以通过更改为sys.stderr来更改out


Python 3.6+ (f-string) Python 3.6+(f 字符串)

def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+
    count = len(it)
    def show(j):
        x = int(size*j/count)
        print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count}", end='\r', file=out, flush=True)
    show(0)
    for i, item in enumerate(it):
        yield item
        show(i+1)
    print("\n", flush=True, file=out)

Python 2 (old-code) Python 2(旧代码)

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

The above suggestions are pretty good, but I think most people just want a ready made solution, with no dependencies on external packages, but is also reusable.上面的建议都不错,但我想大多数人只是想要一个现成的解决方案,不依赖外部包,但也可以重用。

I got the best points of all the above, and made it into a function, along with a test cases.我得到了以上所有优点,并将其与测试用例一起制作成一个函数。

To use it, just copy the lines under "def update_progress(progress)" but not the test script.要使用它,只需复制“def update_progress(progress)”下的行,而不是测试脚本。 Don't forget to import sys.不要忘记导入 sys. Call this whenever you need to display or update the progress bar.每当您需要显示或更新进度条时调用它。

This works by directly sending the "\r" symbol to console to move cursor back to the start.这通过直接将“\r”符号发送到控制台以将光标移回开头来工作。 "print" in python does not recongise the above symbol for this purpose, hence we need 'sys' 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)

This is what the result of the test script shows (The last progress bar animates):这是测试脚本的结果显示(最后一个进度条动画):

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

Try progress from https://pypi.python.org/pypi/progress .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()

The result will be a bar like the following:结果将是如下所示的条形图:

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

for a similar application (keeping track of the progress in a loop) I simply used the python-progressbar :对于类似的应用程序(循环跟踪进度),我只是使用了python-progressbar

Their example goes something like this,他们的例子是这样的,

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

I've just made a simple progress class for my needs after searching here for a equivalent solution.在此处搜索等效解决方案后,我刚刚为我的需要制作了一个简单的进度类。 I thought I might a well post it.我想我可能会很好地发布它。

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)

Example :例子 :

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

Will print the following:将打印以下内容:

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

You can use tqdm :您可以使用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)

In this example the progress bar is running for 5 minutes and it is shown like that:在此示例中,进度条运行了 5 分钟,如下所示:

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

You can change it and customize it as you like.您可以根据需要更改和自定义它。

I like Brian Khuu's answer for its simplicity and not needing external packages.我喜欢Brian Khuu 的答案,因为它简单且不需要外部软件包。 I changed it a bit so I'm adding my version here:我改变了一点,所以我在这里添加我的版本:

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)

It takes the total number of runs ( total ) and the number of runs processed so far ( progress ) assuming total >= progress .假设total >= progress ,它需要运行总数 ( total ) 和到目前为止处理的运行数 ( progress )。 The result looks like this:结果如下所示:

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

I really like the python-progressbar , as it is very simple to use.我真的很喜欢python-progressbar ,因为它使用起来非常简单。

For the most simple case, it is just:对于最简单的情况,它只是:

import progressbar
import time

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

The appearance can be customized and it can display the estimated remaining time.外观可定制,可显示预计剩余时间。 For an example use the same code as above but with:例如,使用与上面相同的代码,但具有:

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

Use this library: fish ( GitHub ).使用这个库: fish ( GitHub )。

Usage:用法:

>>> import fish
>>> while churning:
...     churn_churn()
...     fish.animate()

Have fun!玩得开心!

If it is a big loop with a fixed amount of iterations that is taking a lot of time you can use this function I made.如果它是一个具有固定迭代次数的大循环,需要花费大量时间,您可以使用我制作的这个函数。 Each iteration of loop adds progress.循环的每次迭代都会增加进度。 Where count is the current iteration of the loop, total is the value you are looping to and size(int) is how big you want the bar in increments of 10 ie (size 1 =10 chars, size 2 =20 chars)其中 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 + ']')

example:例子:

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

output:输出:

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

A simple oneliner:一个简单的oneliner:

K = 628318
for k in range(K):
    # your stuff
    print(end="\r|%-80s|" % ("="*int(80*k/(K-1))))
|=====================================================================       |

80 is the length of the bar. 80是条的长度。 Eventually you want a final print() .最终你想要一个最终的print()

And not to forget the digital progress indicator:不要忘记数字进度指示器:

K = 628318
for k in range(K):
    # your stuff
    print(end="\r%6.2f %%" % (k/(K-1)*100))
 94.53 %

It is not to difficult to combine both, if needed.如果需要,将两者结合起来并不难。

The keys are the "Carriage Return" \r and the suppression of the default end="\n" in print .关键是“回车” \rprint中默认end="\n"的抑制。

["

The code below is a quite general solution and also has a time elapsed and time remaining estimate.<\/i>下面的代码是一个非常通用的解决方案,并且还有一个经过时间和剩余时间的估计。<\/b> You can use any iterable with it.<\/i>您可以使用任何可迭代对象。<\/b> The progress bar has a fixed size of 25 characters but it can show updates in 1% steps using full, half, and quarter block characters.<\/i>进度条的固定大小为 25 个字符,但它可以使用完整、半块和四分之一块字符以 1% 的步长显示更新。<\/b> The output looks like this:<\/i>输出如下所示:<\/b><\/p>

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

It is quite straightforward in Python3:在 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')

When running in jupyter notebooks use of normal tqdm doesn't work, as it writes output on multiple lines.在 jupyter 笔记本中运行时,使用普通 tqdm 不起作用,因为它会在多行上写入输出。 Use this instead:改用这个:

import time
from tqdm import tqdm_notebook as tqdm

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

I like this page .我喜欢这个页面

Starts with simple example and moves onto a multi-threaded version.从简单的示例开始,然后转到多线程版本。 Works out of the box.开箱即用。 No 3rd party packages required.不需要第 3 方包。

The code will look something like this:代码将如下所示:

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)

Or here is example to use threads in order to run the spinning loading bar while the program is running:或者这里是使用线程以在程序运行时运行旋转加载栏的示例:

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

Here's a short solution that builds the loading bar programmatically (you must decide how long you want it).这是一个以编程方式构建加载栏的简短解决方案(您必须决定需要多长时间)。

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)
    if i==n: print()

I used format() method to make a load bar.我使用format()方法制作了一个加载栏。 Here is my solution:这是我的解决方案:

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

Output:输出:

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

2022 Answer for simple progress bar without external library没有外部库的简单进度条的2022答案

import time, sys

def progress(size):
    for item in range(size):
        if(item==0):
            print("[",end="")

        elif(item==size-1):
            print("]",end="\n")

        else:
            #main work goes here
            time.sleep(0.1)
            print("%",end="")
            sys.stdout.flush()

progress(50)

If your work can't be broken down into measurable chunks, you could call your function in a new thread and time how long it takes:如果你的工作不能被分解成可测量的块,你可以在一个新线程中调用你的函数并计算它需要多长时间:

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"

You can obviously increase the timing precision as required.您显然可以根据需要提高计时精度。

I like Gabriel answer, but i changed it to be flexible.我喜欢加布里埃尔的回答,但我把它改成了灵活的。 You can send bar-length to the function and get your progress bar with any length that you want.您可以将 bar-length 发送到该函数并获得您想要的任何长度的进度条。 And you can't have a progress bar with zero or negative length.而且你不能有一个零长度或负长度的进度条。 Also, you can use this function like Gabriel answer (Look at the Example #2).此外,您可以使用此功能,如Gabriel answer(请参阅示例 #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)

Result:结果:

This is a simple progress bar.这是一个简单的进度条。

Example #1示例 #1

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

Example #2示例 #2

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

Done.完毕。

Guess i'm a little late but this should work for people working with the current versions of python 3 , since this uses "f-strings" , as introduced in Python 3.6 PEP 498 :猜我有点晚了,但这应该适用于使用当前版本的 python 3的人,因为它使用 Python 3.6 PEP 498中介绍的“f-strings”

Code代码

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

Example例子

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

Output输出

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

Use the progress library !使用进度库

pip install progress

Here is a custom subclass I wrote to format the ETA/Elapsed times into a better readable format:这是我编写的一个自定义子类,用于将 ETA/Elapsed 时间格式化为可读性更好的格式:

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

This is my simple solution:这是我的简单解决方案:

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

A very simple approach:一个非常简单的方法:

def progbar(count: int) -> None:
    for i in range(count):
        print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="\r")
        yield i
    print('\n')

And the usage:以及用法:

from time import sleep

for i in progbar(10):
    sleep(0.2) #whatever task you need to do

Try PyProg.试试 PyProg。 PyProg is an open-source library for Python to create super customizable progress indicators & bars. PyProg 是一个用于 Python 的开源库,用于创建超级可定制的进度指示器和条形图。

It is currently at version 1.0.2;当前版本为 1.0.2; it is hosted on Github and available on PyPI (Links down below).它托管在 Github 上并在 PyPI 上可用(链接如下)。 It is compatible with Python 3 & 2 and it can also be used with Qt Console.它与 Python 3 & 2 兼容,也可以与 Qt 控制台一起使用。

It is really easy to use.它真的很容易使用。 The following code:以下代码:

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

will produce:将产生:

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

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

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

I actually made PyProg because I needed a simple but super customizable progress bar library.我实际上制作了 PyProg,因为我需要一个简单但超级可定制的进度条库。 You can easily install it with: pip install pyprog .您可以使用以下命令轻松安装它: pip install pyprog

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

You can also use enlighten .您也可以使用启蒙 The main advantage is you can log at the same time without overwriting your progress bar.主要优点是您可以同时登录而不会覆盖进度条。

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

It also handles multiple progress bars.它还处理多个进度条。

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

a little more generic answer of jelde015 (credit to him of course) jelde015的一个更通用的答案(当然归功于他)

for updating the loading bar manually will be:手动更新加载栏将是:

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)
                     + ']')

and calling it by:并通过以下方式调用它:

loadingBar(7, 220, 40)

will result:将导致:

007/220 [=                                       ]  

just call it whenever you want with the current i value.只要你想用当前的i值调用它。

set the size as the number of chars the bar should besize设置为条形应为的字符数

I use wget, you have to install the module tho in cmd prompt in windows or terminal if on mac or linux我使用 wget,如果在 mac 或 linux 上,您必须在 windows 或终端的 cmd 提示符下安装模块

pip install wget

It's pretty straight forward, just use the download() function这很简单,只需使用 download() 函数

import wget
url = input("Enter Url to download: ")
wget.download(url)

tqdm is also an option, u have to download the module, too. tqdm 也是一个选项,你也必须下载模块。

pip install tqdm

now make sure to import the module, set the range and pass现在确保导入模块,设置范围并通过

from tqdm import tqdm
for i in tqdm(range(int(9e7))):
    pass

There are a lot of amazing answers already still I would like to share my solution to the progress bar.已经有很多惊人的答案了,我想分享我对进度条的解决方案。

from time import sleep

def progress_bar(progress: float, total: float, width: int = 25):
    percent = width * ((progress + 1) / total)
    bar = chr(9608) * int(percent) + "-" * (width - int(percent))
    print(f"\r|{bar}| {(100/width)*percent:.2f}%", end="\r")

numbers = range(0, 1000)
numbersLen = len(numbers)
for i in numbers:
    sleep(0.01) # Do something usefull here
    progress_bar(i, numbersLen)

EDIT:编辑:

If you are looking for a bar that adjusts it's with based on the terminal's width and a possibility for messages at the end then this works too.如果您正在寻找一个可以根据终端的宽度调整它的条形图,并且最后可能会出现消息,那么这也可以。 Note that the message will disappear if the Terminal gets too narrow as the bar will break if it's too wide for 1 line.请注意,如果终端变得太窄,则该消息将消失,因为如果它对于 1 行来说太宽,则条将中断。

def progressBar(progress: float, total: float, message: str = ""):
    terminalWidth = get_terminal_size().columns
    width = int(terminalWidth / 4)
    percent = width * ((progress + 1) / total)
    bar = chr(9608) * int(percent) + "-" * (width - int(percent))
    if terminalWidth <= 40:
        message = ""
    else:
        message = message + (" " * (int(terminalWidth / 2) - len(message)))
    print(f"\r|{bar}| {(100/width)*percent:.2f}% " + message, end="\r")

There's a lot of good ansers already, but adding this specidfic based upon @HandyGold75 answer, I wanted it to be callabe under a specific context, with an initial msg, plus a timing feedback in seconds at the end.已经有很多好的分析器了,但是根据@HandyGold75 的答案添加这个特定的,我希望它在特定的上下文中被调用,带有初始的消息,加上最后几秒钟的时间反馈。

from time import sleep, time


class ProgressBar:
    def __init__(self, total: float, width: int = 50, msg: str = ""):
    self.total = total
    self.width = width
    self.start: float = time()
    if msg:
        print(f"{msg}")

    def progress(self, progress: float):
        percent = self.width * ((progress) / self.total)
        bar = chr(9608) * int(percent) + "-" * (self.width - int(percent))
        print(
            f"\r|{bar}| {(100/self.width)*percent:.2f}% "
            f"[{progress} of {self.total}]",
            end="\r",
        )

    def __enter__(self):
        return self.progress

    def __exit__(self, type, value, traceback):
        end: float = time()
        print(f"\nFinished after {end - self.start: .3f} seconds.")


# USAGE
total_loops = 150
with ProgressBar(total=total_loops) as progress:
    for i in range(total_loops):
        sleep(0.01)  # Do something usefull here
        progress(i + 1)

@Massagran: It works well in my programs. @Massagran:它在我的程序中运行良好。 Furthermore, we need to add a counter to indicate the loop times.此外,我们需要添加一个计数器来指示循环时间。 This counter plays as the argument of the method update .此计数器用作方法update的参数。 For example: read all lines of a test file and treat them on something.例如:读取测试文件的所有行并将它们处理为某事。 Suppose that the function dosth() do not concern in the variable i .假设函数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()

The variable i controls the status of pbar via the method update变量i通过方法update控制pbar的状态

You should link the progress bar to the task at hand (so that it measures the progress :D).您应该将进度条链接到手头的任务(以便它衡量进度:D)。 For example, if you are FTPing a file, you can tell ftplib to grab a certain size buffer, let's say 128K, and then you add to your progress bar whatever percentage of the filesize 128k represents.例如,如果您正在通过 FTP 传输文件,您可以告诉 ftplib 获取某个大小的缓冲区,比如说 128K,然后您将 128k 代表的文件大小百分比添加到进度条。 If you are using the CLI, and your progress meter is 20 characters long, you would add one character when 1/20th of the file had transferred.如果您使用的是 CLI,并且您的进度条有 20 个字符长,那么您将在文件传输 1/20 时添加一个字符。

use the os_sys lib:使用os_sys库:

i use it for many types of bars, example:我将它用于多种类型的酒吧,例如:

from os_sys.progress import bar as Bar
bar = Bar('progresing: ', max=20)
for i in range(20):
    #do somthing
    bar.next()
bar.finish()

your output will be:你的输出将是:

procesing:  |######                          | 2/10

read more in the discription of os_sys在 os_sys 的描述中阅读更多内容

This is a simple way to create a progressbar这是创建进度条的简单方法

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)

This progress bar shows points of each 2 percent complete and numbers for each 10 percent complete.此进度条显示每完成 2% 的分数和每完成 10% 的数字。

import sys

def ProgressBar (num, total, nextPercent, nextPoint):
    num = float (num)
    total = float (total) - 1
    if not nextPoint:
        nextPoint = 0.0
    if not nextPercent:
        nextPoint += 2.0
        sys.stdout.write ("[0%")
        nextPercent = 10
    elif num == total:
        sys.stdout.write ("100%]\n")
        nextPercent += 10
    elif not nextPoint:
        nextPoint = 0.0
    elif num / total * 100 >= nextPercent:
        sys.stdout.write (str(int (nextPercent)) + "%")
        nextPercent += 10
    elif num / total * 100 >= nextPoint:
        sys.stdout.write (":")
        nextPoint += 2
    return (nextPercent, nextPoint)

nextPercent, nextPoint = 0, 0
total = 1000

for num in range (total):
    nextPercent, nextPoint = ProgressBar (num, total, nextPercent, nextPoint)

Results:结果:

>>> 
[0%::::10%:::::20%:::::30%:::::40%:::::50%:::::60%:::::70%:::::80%:::::90%:::::100%]
>>> 

A simple solution here !这里有一个简单的解决方案!

void = '-'
fill = '#'
count = 100/length
increaseCount = 0
for i in range(length):
    print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
    increaseCount += count
    time.sleep(0.1)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')

Note : You can modify the fill and the "void" character if you want.注意:您可以根据需要修改填充和“空白”字符。

The loading bar (picture)加载栏(图片)

Progressbar for iterrows. iterrows 的进度条。 Adaptation of @eusoubrasileiro code for displaying progress when looping through rows of a dataframe. @eubrasileiro 代码的改编,用于在循环遍历数据帧的行时显示进度。 Additionally shows percentage, ith/count, elapsed seconds, iters/sec, remaining seconds.此外还显示百分比、第 i 个/计数、经过的秒数、迭代次数/秒、剩余秒数。 Allows specifying an nth updating count (per).允许指定第 n 个更新计数(每)。

import time
import sys
def progressbar_iterrows(df, prefix="", size=60, file=sys.stdout, per=1000):
    count = len(df)
    t = 0
    def show(j,elapsed):
        avg = 0 if elapsed == 0 else j/elapsed
        remaining = 0 if avg == 0 else (count-j)/avg
        x = int(size*j/count)
        file.write("%s[%s%s] %i%% %i/%i elapsed:%i %i/sec remaining:%i\r" % (prefix, "#"*x, "."*(size-x), j/count, j, count, elapsed, avg, remaining))
        file.flush()
    file.write("Initializing ...\r")
    file.flush()
    for i, item in df.iterrows():
        yield i,item
        if t == 0:
            t = time.time()
        if i % per == 0:
            show(i,time.time()-t)
    file.write("\n")
    file.flush()

Usage:用法:

    for n,r in progressbar_iterrows(br_b_sections_df, "Processed: "):
        # do something

Output:输出:

Processed: [........................] 0% 5000/28751240 elapsed:12 413/sec remaining:55054
["
from IPython.display import clear_output
progress_bar=u"\u001b[7m Loading: "
for i in range(100):
    clear_output(wait=True)
    progress_bar+=u"\u001b[7m "
    print(progress_bar+str(i+1)+"%")
    time.sleep(0.03) #you can change the speed

堆栈到博客进度 display.gif

None of the answers posted completely addressed my needs.发布的答案都没有完全满足我的需求。 So I wrote my own as shown above.所以我写了我自己的,如上图所示。 The features I needed:我需要的功能:

  • Pass only the step number and total number of steps and it does the difficult job of calculating percentage complete.只传递步骤数和总步骤数,它完成计算完成百分比的困难工作。
  • Using only 60 character spaces, divide them into 240 "ticks" to give better granular display from .25 % to 100%.仅使用 60 个字符空格,将它们分成 240 个“刻度”,以提供从 0.25% 到 100% 的更好的粒度显示。
  • Support for prepending a title.支持添加标题。
  • Optional percentage complete at end of line.可选百分比在行尾完成。
  • Variable length progress bar that defaults to 60 characters or 240 "ticks".默认为 60 个字符或 240 个“刻度”的可变长度进度条。

How to Call the Progress Display如何调用进度显示

Calling the progress display is pretty straight forward.调用进度显示非常简单。 For the above sample .gif the function was called using:对于上面的示例.gif ,使用以下方法调用该函数:

percent_complete(step, total_steps, title="Convert Markdown")

The total_steps was about 2,500 for len(rows) in Stack Exchange Data Dump in CSV format. CSV 格式的 Stack Exchange 数据转储中len(rows)total_steps约为 2,500。 The step was the current row number as each Stack Exchange Markdown Q&A was converted to Kramdown (for GitHub Pages).step是当前行号,因为每个 Stack Exchange Markdown Q&A 都被转换为 Kramdown(用于 GitHub 页面)。

Python Code Python代码

The code is straight forward, but a bit longer than the other answers:代码很简单,但比其他答案长一点:

def percent_complete(step, total_steps, bar_width=60, title="", print_perc=True):
    import sys

    fill = "▒"                      # Fill up to bar_width
    utf_8s = ["▉", "▎", "▌", "▊"]   # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4
    perc = 100 * float(step) / float(total_steps)
    max_ticks = bar_width * 4
    num_ticks = int(round(perc / 100 * max_ticks))
    full_ticks = num_ticks / 4      # Number of full blocks
    part_ticks = num_ticks % 4      # Size of partial block (array index)

    disp = bar = ""                 # Blank out variables
    bar += utf_8s[0] * full_ticks   # Add full blocks into Progress Bar

    # If part_ticks is zero, then no partial block, else append part char
    if part_ticks > 0:
        bar += utf_8s[part_ticks]

    # Pad Progress Bar with fill character
    bar += fill * int((max_ticks/4 - float(num_ticks)/4.0))

    if len(title) > 0:
        disp = title + ": "         # Optional title to progress display

    disp += bar                     # Progress bar to progress display
    if print_perc:
        # If requested, append percentage complete to progress display
        if perc > 100.0:
            perc = 100.0            # Fix "100.04 %" rounding error
        disp += " {:6.2f}".format(perc) + " %"

    # Output to terminal repetitively over the same line using '\r'.
    sys.stdout.write("\r" + disp)
    sys.stdout.flush()

Python Code Notes Python 代码注释

A few points:几点:

  • The [ .... ] bracket placeholders are not necessary because there is the fill characters that serve the same purpose. [ .... ]括号占位符不是必需的,因为存在用于相同目的的填充字符。 This saves two extra characters to make the progress bar wider.这会节省两个额外的字符,使进度条变宽。
  • The bar_width keyword parameter can be used depending on screen width. bar_width关键字参数可以根据屏幕宽度使用。 The default of 60 seems a good fit for most purposes.默认值60似乎适合大多数用途。
  • The print_perc=True keyword parameter default can be overridden by passing print_perc=False when calling the function.可以通过在调用函数时传递print_perc=False来覆盖print_perc=True关键字参数默认值。 This would allow a longer progress bar.这将允许更长的进度条。
  • The title="" keyword parameter defaults to no title. title=""关键字参数默认为无标题。 Should you desire one use title="My Title" and : will automatically be added to it.如果您希望使用title="My Title"并且:将自动添加到其中。
  • When your program finishes remember to call sys.stdout.write("\\r") followed by sys.stdout.flush() to clear the progress display line.当您的程序完成时,请记住调用sys.stdout.write("\\r")后跟sys.stdout.flush()以清除进度显示行。

Summary概括

This answer is a bit longer than the others but it's important to note it's a full solution, not part of a solution that you need to add more code to.这个答案比其他答案要长一些,但重要的是要注意它是一个完整的解决方案,而不是您需要添加更多代码的解决方案的一部分。

Another point is this solution has no dependencies and nothing extra to install.另一点是这个解决方案没有依赖项,也不需要安装任何额外的东西。 The UTF-8 character set is supported by Python and gnome-terminal was no extra setup required. Python 支持 UTF-8 字符集,不需要额外设置gnome-terminal If you are using Python 2.7 you might require # -*- coding: utf-8 -*- after the shebang.如果您使用的是 Python 2.7,您可能需要# -*- coding: utf-8 -*-在 shebang 之后。 IE as the second line of your program. IE 作为程序的第二行。

The function could be converted to a class with separate init , update , pause (for printing debug stuff to the screen), resume and close methods.该函数可以转换为具有单独initupdatepause (用于将调试内容打印到屏幕)、 resumeclose方法的类。

This function was converted from a bash script.此函数是从 bash 脚本转换而来的。 The bash script would display Sony TV volume with libnotify-bin (pop-up bubble message) whenever TV volume was changed.每当电视音量发生变化时,bash 脚本都会使用libnotify-bin (弹出气泡消息)显示索尼电视音量。 If you are interested in the bash version, please post a comment below.如果您对 bash 版本感兴趣,请在下面发表评论。

#doesnt affect actual execution
#based on events and consumption in background
#may be that actual process completes a bit earlier than progress shows 99%
#make an instance with number of elements in a loop
#in each iteration call the method current_progress

import time
from math import ceil
import os
import sys
from threading import Thread
class progress_bar(object):
 def __init__(self,total_elements,length_bar=25):
  self.length_bar=length_bar
  self.total_elements=total_elements
  self.singleweight=(float(1)/float(total_elements))*100
  self.done=0
  self.qt=[0]
  self.call_count=0
  t=Thread(target=self.display_progress)
  t.start()
 def current_progress(self):
  self.done+=1
  self.qt=[self.done]+self.qt
 def display_progress(self):
  while True:
   try:
    done=self.qt.pop()
   except:
    continue
   else:
    self.call_count+=1
    self.progress=self.singleweight*done
    fill=ceil(self.progress)
    bar=int((fill*self.length_bar)/100)*"|"
    bar="["+bar+str(fill)+"%"
    barp=bar
    for i in range(0,self.length_bar+3-(len(bar))):
     barp=barp+"_"
    barp=barp+"]"
    if self.progress <= 100:
     os.system("clear")
     print("Progress:",barp, sep=' ', end='\n', file=sys.stdout, flush=True)
    if self.call_count == self.total_elements:
     break
  else:
   pass

Inspired by many of the answers with no package dependency, I am sharing my implementation here.受到许多没有 package 依赖的答案的启发,我在这里分享我的实现。 The function to be used in any loop expects the current iteration number, the total number of iterations, and the initial time.用于任何循环的 function 需要当前迭代次数、迭代总数和初始时间。

import time    
def simple_progress_bar(i: int, n: int, init_time: float):
    avg_time = (time.time()-init_time)/(i+1)
    percent = ((i+1)/(n))*100
    print(
        end=f"\r|{'='*(int(percent))+'>'+'.'*int(100-int(percent))}|| " + \
        f"||Completion: {percent : 4.3f}% || \t "+ \
        f"||Time elapsed: {avg_time*(i+1):4.3f} seconds || \t " + \
        f"||Remaining time: {(avg_time*(n-(i+1))): 4.3f} seconds."
    )
    return



N = 325
t0 = time.time()
for k in range(N):
    # stuff goes here #
    time.sleep(0.0001)
    # stuff goes here #
    
    simple_progress_bar(k, N, t0)

pip install progressbar2

进度条 进度条 进度条 进度条 进度条

import os
import time
import progressbar 

os.environ['PYCHARM_HOSTED'] = '1' # https://github.com/WoLpH/python-progressbar/issues/237

class COLOR: # https://stackoverflow.com/a/287944/11465149
    YELLOW    = '\033[93m'
    GREEN     = '\033[92m'
    RED       = '\033[91m'
    BOLD      = '\033[1m'
    ENDC      = '\033[0m'

widgets=[
    'FILE.JSON ',
    COLOR.YELLOW          , progressbar.Percentage()                        , COLOR.ENDC,
    COLOR.RED + COLOR.BOLD, progressbar.Bar(left=' ', marker='━', right=' '), COLOR.ENDC,
    COLOR.YELLOW          , progressbar.Timer()                             , COLOR.ENDC
]

for i in progressbar.progressbar(range(100), widgets=widgets):
    time.sleep(0.01)
    if i == 99:
        widgets[4] = COLOR.GREEN

Use enumerate(...progressbar(max_value=...) + this in case you want to use it as a download progressbar使用enumerate(...progressbar(max_value=...) + this如果您想将其用作下载进度条

You can use the rich library, wich has really good terminal styling, including progress bars.您可以使用丰富的库,它具有非常好的终端样式,包括进度条。 First run the followng command: pip install rich首先运行以下命令: pip install rich

Example from docs:来自文档的示例:

import time
from rich.progress import track

for i in track(range(20), description="Processing..."):
    time.sleep(1)  # Simulate work being done

Here is a very simple version, in case you have a loop and just want to get an idea of progression of iterations, such as a dot for every, say, 5000 iterations.这是一个非常简单的版本,以防您有一个循环并且只想了解迭代的进展情况,例如每 5000 次迭代的一个点。

my_list = range(0,100000)

counter = 0
for x in my_list:
    #your code here

    counter = counter + 1
    if counter % 5000 == 0:
        print(".", end="") # end="" avoids a newline, keeps dots together

print() #this makes sure whatever you print next is in a new line

my_list is not part of the scheme. my_list 不是该计划的一部分。 Use your own iterable, whatever you are looping over.使用您自己的可迭代对象,无论您在循环什么。 This version doesn't tell you ahead of time how many total iterations.此版本不会提前告诉您总迭代次数。

Wanted to have the smallest and fewest lines ,想拥有最小最少的线条,

for i in range(1,10):
 print("Progress: "+i*"#" , end="\r")
 time.sleep(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM