为Python代码添加酷炫的进度条

自己设计

方式1:

在这里插入图片描述

代码:

sample = 9
for i in range(sample):
    percent = 100 * (i + 1) / sample
    print("[" + "=" * int(100 * (i + 1) / sample) + '>' + '·' * (100 - int(100 * (i + 1) / sample)) + ']'
          + "[" + '%.2f' % percent + "%]")

方式2:

在这里插入图片描述

import sys
import time


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


for i in progressbar(range(15), "Computing: ", 40):
    time.sleep(0.1)

将上面代码封装成一个类:

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 range(progress.total):
    progress.current += 1
    progress()
    sleep(0.1)
progress.done()

在这里插入图片描述

解释:为什么不用print?因为sys.stdout就是print的一种默认输出格式,而sys.stdout.write()可以不换行打印,sys.stdout.flush()可以立即刷新输出的内容

第三方库

tqdm

安装:pip install tqdm

方式1:

from tqdm import trange
import time
for i in trange(10): 
    time.sleep(1)

在这里插入图片描述

方式2:

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43141320/article/details/107676515