Python - 进度条

Python - 进度条

Max.Bai

2018-08

sys.stdout实现进度条效果

直接上代码:

#!/usr/bin/env python3
# _*_ coding:utf-8 _*_

'''
Progress bar
Max.Bai
2018-08
'''

import sys
import time


def print_progress_bar(total, current):
    '''progress bar with count and percent
    
    Arguments:
        total {int} -- total count
        current {int} -- current count
    '''

    bar_length = 100
    percent = round(current*100/total, 2)
    percent_count = int(current*100/total)
    half = 1 if percent - percent_count>0.5 else 0

    pstr = '\r[{}{}{}]  [{}/{}] {}%'.format('|'*percent_count, '='*half, ' '*(bar_length-percent_count-half), current, total, percent)
    sys.stdout.write(pstr + '\b' * (len(pstr) - percent_count - 2) )
    sys.stdout.flush()


def progress_bar_demo():
    '''
    demo
    '''
    for i in range(891):
        print_progress_bar(890, i)
        time.sleep(0.1)


if __name__ == '__main__':
    progress_bar_demo()

看下效果:

解释一下:

\r  表示回到行头

\b 表示光标当前位置退一格

扫描二维码关注公众号,回复: 2979518 查看本文章

当然也有功能强大的库

1. progressbar (http://code.google.com/p/python-progressbar/)

2. progressive (https://pypi.python.org/pypi/progressive)

猜你喜欢

转载自blog.csdn.net/max229max/article/details/82148746