Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >在python中实现进度条

在python中实现进度条

作者头像
羽翰尘
修改于 2019-11-26 07:43:10
修改于 2019-11-26 07:43:10
1.1K0
举报
文章被收录于专栏:技术向技术向

本文由腾讯云+社区自动同步,原文地址 http://blogtest.stackoverflow.club/progressbar-in-python/

试图通过pip

在python2中可以很方便的安装progressbar模块,但是python3中会报如下错误:

代码语言:txt
AI代码解释
复制
Collecting progressbar
  Downloading progressbar-2.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-ghlr5eic/progressbar/setup.py", line 5, in <module>
        import progressbar
      File "/tmp/pip-build-ghlr5eic/progressbar/progressbar/__init__.py", line 59, in <module>
        from progressbar.widgets import *
      File "/tmp/pip-build-ghlr5eic/progressbar/progressbar/widgets.py", line 121, in <module>
        class FileTransferSpeed(Widget):
      File "/home/wenfeng/anaconda3/envs/tensorflow/lib/python3.6/abc.py", line 133, in __new__
        cls = super().__new__(mcls, name, bases, namespace, **kwargs)
    ValueError: 'format' in __slots__ conflicts with class variable
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ghlr5eic/progressbar/

显然,这是由于版本差异造成的。所以,可以考虑自己实现一个progressbar了。

自己造轮子

  • 类的实现
代码语言:txt
AI代码解释
复制
#!/usr/local/lib
# -*- coding: UTF-8 -*-
import sys, time
class ShowProcess():
    """
    显示处理进度的类
    调用该类相关函数即可实现处理进度的显示
    """
    i = 0 # 当前的处理进度
    max_steps = 0 # 总共需要处理的次数
    max_arrow = 50 #进度条的长度
    # 初始化函数,需要知道总共的处理次数
    def __init__(self, max_steps):
        self.max_steps = max_steps
        self.i = 0
    # 显示函数,根据当前的处理进度i显示进度
    # 效果为[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]100.00%
    def show_process(self, i=None):
        if i is not None:
            self.i = i
        else:
            self.i += 1
        num_arrow = int(self.i * self.max_arrow / self.max_steps) #计算显示多少个'>'
        num_line = self.max_arrow - num_arrow #计算显示多少个'-'
        percent = self.i * 100.0 / self.max_steps #计算完成进度,格式为xx.xx%
        process_bar = '[' + '>' * num_arrow + '-' * num_line + ']'\
                      + '%.2f' % percent + '%' + '\r' #带输出的字符串,'\r'表示不换行回到最左边
        sys.stdout.write(process_bar) #这两句打印字符到终端
        sys.stdout.flush()
    def close(self, words='done'):
        print ''
        print words
        self.i = 0
if __name__=='__main__':
    max_steps = 100
    process_bar = ShowProcess(max_steps)
    for i in range(max_steps + 1):
        process_bar.show_process()
        time.sleep(0.05)
    process_bar.close()
 
  • 测试
代码语言:txt
AI代码解释
复制
process_bar = ShowProcess(max_steps) # 1.在循环前定义类的实体, max_steps是总的步数    
for i in range(max_steps + 1):    
    process_bar.show_process()      # 2.显示当前进度
    time.sleep(0.05)    
process_bar.close('done')            # 3.处理结束后显示消息
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
如何在 Canopy 中导入 scikit-learn
在 Canopy 中导入 scikit-learn 是一个简单的过程。首先,确保你已经安装了 scikit-learn,然后你可以像在其他 Python 环境中一样导入它。
华科云商小徐
2025/02/05
840
获取没有设置TTL的key
在运维Redis的时候,总会遇到使用不规范的业务设计,比如没有对key设置ttl,进而导致内存空间吃紧,通常的解决方法是在slave上dump 出来所有的key ,然后对文件进行遍历再分析。遇到几十G的Redis实例,dump + 分析 会是一个比较耗时的操作,为此,我开发了一个小脚本直接连接Redis 进行scan 遍历所有的key,然后在检查key的ttl,将没有ttl的key输出到指定的文件里面。
用户1278550
2018/08/09
1.6K0
pip3 install mysqlclient 报错 “/bin/sh: 1: mysql_config: not found”的解决方法
报错信息 [root@localhost hc_BgpServer]# pip3 install mysqlclient Collecting mysqlclient Downloading https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz (85kB) 100% |██
一朵灼灼华
2022/08/05
1.1K0
python安装、数据类型和变量
2018.06.06 1.1为什么要学习python 学习方法: 边看边做不能只看不做 笔记要记录详细
py3study
2020/01/06
6100
python安装、数据类型和变量
Python使用扩展库progressbar显示进度条
首先https://pypi.python.org/pypi/progressbar2/3.20.0下载whl文件,然后使用pip进行本地安装。 导入后面代码所需要的库: import time import logging import progressbar 执行下面的代码: bar = progressbar.ProgressBar() for i in bar(range(100)): time.sleep(0.02) 运行效果如图(文中截图只显示最终运行结果,请自行运行代码观看运行过程,下
Python小屋屋主
2018/04/16
2.6K0
Python使用扩展库progressbar显示进度条
【Python报错】有效解决pip3安装matplotlib!
问题 使用 pip3 install matplotlib 报错: Running setup.py bdist_wheel for pillow ... error Complete output from command /usr/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-prbp5o66/pillow/setup.py';f=getattr(tokenize, 'open', open)(__
Lokinli
2023/03/09
1K0
pip 安装mysqlclient报错OSError: mysql_config not found
执行pip install mysqlclient报错信息如下: [root@CentOS7-demo bin]# pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found T
周小董
2019/03/25
5.2K0
给Python代码加上酷炫进度条的几种姿势
大家好,在下载某些文件的时候你一定会不时盯着进度条,在写代码的时候使用进度条可以便捷的观察任务处理情况,除了使用print来打印之外,今天本文就介绍几种给你的Python代码加上酷炫的进度条的方式。
刘早起
2020/06/04
9730
python的distutils、setuptools模块
python包在开发中十分常见,一般的使用套路是所有的功能做一个python模块包,打包模块,然后发布,安装使用。打包和安装包就是最常见的工作。学习中遇到distutils和setuptools两种打包的工具。
狼啸风云
2023/10/07
9890
python的distutils、setuptools模块
Python: 安装lz4-0.10.1痛苦经历
因为项目的需求,要 lz4.0.10.1 的,因为本机已经有一个 1.1.0 版本的,所以必须先卸掉,然后我差点没疯了(手动微笑)
Lin_R
2018/10/22
3.6K0
Python 中的多种进度条实现方法
文本进度条是在命令行界面中显示的一种基本的进度展示方法。可以使用字符或符号来构建文本进度条。这种方式很最简单, 就是使用print实现。
不止于python
2023/10/24
1.1K0
Python 中的多种进度条实现方法
Python显示进度条,实时显示处理进度
发现了一个工具,tqdm,大家可以了解一下,使用tqdm就不需要自己来写代码显示进度了 在大多数时候,我们的程序会一直进行循环处理。这时候,我们非常希望能够知道程序的处理进度,由此来决定接下来该做些什么。接下来告诉大家如何简单又漂亮的实现这一功能。 #如何使用这个类 使用这个类很简单,只需要两步即可完成,如下:
py3study
2020/01/08
4.3K0
python文件类型
查看系统中的python版本,如系统中没有python可以到 python.org 网站下载python,支持linux、windows、macos系统。下文可以看到系统已经安装过了python2.7版本。
嘻哈记
2021/03/20
9010
【Python基础】08、Python模
 可以将代码量较大的程序分割成多个有组织的、彼此独立但又能互相交互的代码片段,这些自我包含的有组织的代码段就是模块
py3study
2020/01/06
1.8K0
CentOS下使用pip安装python依赖报错的解决思路
前两天在CentOS上安装docker-compose的时候遇到了pip安装依赖报错,并且经过一番查找,也得到了解决方案,最关键的是经过这个经验,我知道了pip在python2的版本中也有一个官方指定的最后一个支持版本,这篇文章就来记录这个事情,以便后续同类报错可以少走弯路。
Hopetree
2023/08/16
9340
windows环境下用pip安装pyau
1、不能直接使用win+r运行cmd并使用pip,必须点击开始->windows系统->命令提示符,右键->以管理员身份运行
py3study
2020/01/17
1.2K0
python实现进度条
import sys import time def view_bar(num, total):   rate = num / total   rate_num = int(rate * 100)   r = '\r[%s%s]%d%% ' % ("="*num, " "*(100-num), num, )   sys.stdout.write(r)   sys.stdout.flush() #在python中,输出stdout(标准输出)可以使用sys.stdout.write if __name__ == '__main__':   for i in range(0, 101):     time.sleep(0.1)     view_bar(i, 100) ============================================================================== import os,sys,string    import time    def view_bar(num=1, sum=100, bar_word=":"):        rate = float(num) / float(sum)        rate_num = int(rate * 100)        print '\r%d%% :' %(rate_num),        for i in range(0, num):            os.write(1, bar_word)            sys.stdout.flush()    if __name__ == '__main__':       for i in range(0, 101):           time.sleep(0.1)           view_bar(i, 100)   ========================================================================== import sys, time for i in range(5):     sys.stdout.write(' ' * 10 + '\r')     sys.stdout.flush()     print i  sys.stdout.write(str(i) * (5 - i) + '\r')     sys.stdout.flush()     time.sleep(1) ========================================================================== import time import progressbar p = progressbar.ProgressBar() N = 1000 for i in p(range(N)):     time.sleep(0.01) ============================================================================== import time import progressbar p = progressbar.ProgressBar() N = 1000 p.start(N) for i in range(N):     time.sleep(0.01)     p.update(i+1) p.finish() ================================================================================= import time import progressbar bar = progressbar.ProgressBar(widgets=[     ' [', progressbar.Timer(), '] ',     progressbar.Percentage(),     ' (', progressbar.ETA(), ') ', ]) for i in bar(range(1000)):     time.sleep(0.01) #说明如下 'Timer',          # 计时器 'ETA',            # 预计剩余时间 'AbsoluteETA',    # 预计结束的绝对时间,耗时很长时使用较方便 'Percentage',     # 百分比进度,30% 'SimpleProgress', # 计数进度,300/1000 'Counter',        # 单纯计数 'Bar'             # “#”号进度条 ===
py3study
2020/01/14
1.1K0
open-falcon ---安装Dashboard时候报错"SSLError: The read operation timed out"
在部署open-falcon环境过程中,安装Dashboard时候报错"SSLError: The read operation timed out"。如下: [root@open dashboard]# ./env/bin/pip install -r pip_requirements.txt Downloading/unpacking Flask==0.10.1 (from -r pip_requirements.txt (line 1)) Downloading Flask-0.10.1.tar.
洗尽了浮华
2018/01/23
1.1K0
centos7.6安装psycopg2
如果有下面的异常信息,则先安装postgresql-devel* yum install postgresql-devel* 再安装 pip3 install psycopg2 异常: Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) ERROR: Command errored out with exit status 1: command: /usr/local/python3/bin/python3.8
李玺
2021/11/22
6500
linux安装mysqlclient报错
错误信息 Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module>
Wyc
2018/10/08
2.6K0
相关推荐
如何在 Canopy 中导入 scikit-learn
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档