自定义python进度条

代码 :

import sys
import time


class ProgressBar:

    def __init__(self, total, desc="", size=40, symbol='█', file=sys.stderr):
        self.total = total  # 总长度
        self.desc = desc  # 文字说明
        self.symbol = symbol  # 进度条标志
        self.size = size  # 进度条总长度
        self.file = file  # 输出方式
        self.current = 0  # 当前长度
        self.start = time.time()
        self.update(0)

    def update(self, step=1):
        """更新进度条"""
        # 更新当前长度
        self.current += step
        # 确定进度条字符的个数
        x = int(self.current / self.total * self.size)
        # 计算百分比
        percentage = int(self.current / self.total * 100)
        # 计算用时
        d = int(time.time() - self.start)
        duration = f'{d // 60:02d}:{d % 60:02d}'
        # 输出
        # \r:回车,即将光标移到行首,但是不会移到下一行,如果继续输入的话会覆盖掉前面的内容
        fmt = f'\r{self.desc} |{self.symbol * x}{" " * (self.size - x)}| [{self.current}/{self.total}] [{percentage}%] [{duration}]'
        print(fmt, file=self.file, end='')


if __name__ == '__main__':
    bar = ProgressBar(total=15, desc='测试中...')
    for i in range(15):
        bar.update(1)
        time.sleep(1)

运行效果:

1.pycharm:(理想效果)

 

2.命令行执行:(理想效果)

3.sublime_text:

参考:

        给Python代码加上酷炫进度条的几种姿势 - 知乎 (zhihu.com)

  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值