python 实现各种进度条

1. 时间进度条

class Tiao(object):
    def __init__(self):
        self.obj1 = datetime.timedelta(seconds=1)
        self.var = '%H:%M:%S'

    def add(self, var):
        a = datetime.datetime.strptime(var, self.var)
        b = a + self.obj1
        return str(b.strftime(self.var))

    def str_time(self, var3):
        a, b, c = [int(i) for i in var3.split(":")]
        a *= 3600
        b *= 60
        return a + b + c

    def yuan(self, var1, var2):
        """
        计算 百分比
        :param var1: 现在时间
        :param var2: 总时间
        """
        var1 = self.str_time(var1)
        var2 = self.str_time(var2)
        return '{:.2%}'.format(var1/var2)


def zhanshi(var):
    a = Tiao()
    b = "00:00:00"
    while True:
        if var == b:
            break
        b = a.add(b)
        print('\r%s/%s (%s)' % (b, var, a.yuan(b, var)), end='')
        time.sleep(1)


zhanshi("00:25:37")

# 结果
00:01:39/00:25:37 (6.44%)

 2. # 号进度条

#!/usr/bin/env python3
import time


class Index(object):
    def __init__(self, number=50, decimal=2):
        """
        :param decimal: 你保留的保留小数位
        :param number: # 号的 个数
        """
        self.decimal = decimal
        self.number = number
        self.a = 100/number   # 在百分比 为几时增加一个 # 号

    def __call__(self, now, total):
        # 1. 获取当前的百分比数
        percentage = self.percentage_number(now, total)

        # 2. 根据 现在百分比计算
        well_num = int(percentage / self.a)
        # print("well_num: ", well_num, percentage)

        # 3. 打印字符进度条
        progress_bar_num = self.progress_bar(well_num)

        # 4. 完成的进度条
        result = "\r%s %s" % (progress_bar_num, percentage)
        return result

    def percentage_number(self, now, total):
        """
        计算百分比
        :param now:  现在的数
        :param total:  总数
        :return: 百分
        """
        return round(now / total * 100, self.decimal)

    def progress_bar(self, num):
        """
        显示进度条位置
        :param num:  拼接的  “#” 号的
        :return: 返回的结果当前的进度条
        """
        # 1. "#" 号个数
        well_num = "#" * num

        # 2. 空格的个数
        space_num = " " * (self.number - num)

        return '[%s%s]' % (well_num, space_num)



index = Index()

start = 371
for i in range(start + 1):
    print(index(i, start), end='')
    time.sleep(0.01)
    # \r 返回本行开头
    # end : python 结尾不加任何操作, 默认是空格

  

  

posted @ 2018-09-22 18:45  如梦dream  阅读(18495)  评论(0编辑  收藏  举报