• [ python ] 使用sys模块实现进度条


      在写网络IO传输的时候, 有时候需要进度条来显示当前传输进度,使用 sys 模块就可以实现:

      sys.stdout.write() 这个函数在在控制台输出字符串不会带任何结尾,这就意味着这个输出还没有结束,可以使用 sys.stdout.flush() 函数将输出暂时打印到控制台上,

    然后可以使用 ' ' 在回到首行继续输出。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import sys, time
    bar_length = 100   # 进度条为 100 个 '='
    x = 0
    y = 1000
    mode = '下载中'
     
    while x != y:
        x += 10
        percent = float(x) / float(y)          # 计算是否是断点续传,当为 x 为0 表示第一次传输,当 x 为非零数 表示续传;
        hashes = '=' * int(percent * bar_length)    # 计算进度条百分比, 1% 代表 1个'=' 10% 代表 10个 '='
        spaces = ' ' * (bar_length - len(hashes))   # 计算进度条剩余长度,用空格表示
        # 
     要写在行首,mode:模式, x:增长长度,y:总大小, percent*100 增长的百分比, hashes: 进度条长度 spaces: 空格长度  hashes+spaces = 100%
        sys.stdout.write('
    %s:%.2f/%.2f %d%% [%s]' %(mode, x, y, percent*100, hashes+spaces))
        sys.stdout.flush()
        time.sleep(0.2)
    

    运行如图:

  • 相关阅读:
    MongoDb
    js暴露内部方法属性等
    JS闭包
    k8s设计模式
    scrum
    死锁
    Linux下安装php 扩展fileinfo
    linux中whereis、which、find、location的区别和用法
    Linux 命令学习记录
    windows 下 redis 的安装及使用
  • 原文地址:https://www.cnblogs.com/hukey/p/8847066.html
Copyright © 2020-2023  润新知