无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

python 进度条 ,Python 实现进度条的代码方式(图文详解1)

Python Micheal 5个月前 (04-22) 106次浏览 已收录 扫描二维码
文章目录[隐藏]
python 进度条 ,Python 实现进度条的代码方式(图文详解1)

python 进度条

python 进度条,Python 实现进度条的代码方式(图文详解1)

Python 中实现进度条的常见方式有以下几种:

  1. 使用 tqdm 库
    • 底层原理tqdm 库使用 ANSI 转义序列在控制台中输出动态进度条,通过跟踪任务的当前进度并计算剩余时间来实现进度条的动态更新。
    • 使用步骤:
      1. 安装 tqdm 库: pip install tqdm
      2. 导入 tqdm 模块: from tqdm import tqdm
      3. 在遍历或循环中使用 tqdm 包装迭代器: for i in tqdm(range(100)):
    • 示例代码:
      from tqdm import tqdm
      import time
      
      for i in tqdm(range(100)):
          time.sleep(0.1)
      
  2. 手动实现进度条
    • 底层原理: 手动实现进度条需要控制光标位置,并使用特殊字符如#=等来表示进度。通过输出回退和覆盖的方式来更新进度条。
    • 使用步骤:
      1. 确定进度条的总长度和当前进度
      2. 计算进度条的显示比例
      3. 使用特殊字符输出进度条并更新光标位置
      4. 添加其他信息如百分比、剩余时间等
    • 示例代码:
      import time
      import sys
      
      def progress_bar(progress, total, length=50, fill='█', empty='-'):
          percent = 100 * (progress / float(total))
          filled = int(length * progress // total)
          bar = fill * filled + empty * (length - filled)
          print(f'\r[{bar}] {percent:.2f}%', end='\r')
          if progress == total:
              print()
      
      # 使用示例
      for i in range(101):
          progress_bar(i, 100)
          time.sleep(0.1)
      
  3. 使用 sys.stdout.write() 实现
    • 底层原理: 使用 sys.stdout.write() 在控制台直接输出进度条,并使用\r回车符更新光标位置来实现进度条的动态更新。
    • 使用步骤:
      1. 确定进度条的总长度和当前进度
      2. 计算进度条的显示比例
      3. 使用 sys.stdout.write() 输出进度条并使用\r回车符更新光标位置
      4. 添加其他信息如百分比、剩余时间等
    • 示例代码:
      import sys
      import time
      
      def progress_bar(progress, total, length=50):
          percent = 100 * (progress / float(total))
          bar = '█' * int(length * progress // total) + '-' * (length - int(length * progress // total))
          sys.stdout.write(f"\r[{bar}] {percent:.2f}%")
          sys.stdout.flush()
          if progress == total:
              sys.stdout.write('\n')
      
      # 使用示例
      for i in range(101):
          progress_bar(i, 100)
          time.sleep(0.1)
      

以上三种方式都可以实现进度条的显示,选择哪种方式取决于具体的需求和个人偏好。tqdm 库提供了更丰富的功能和样式选择,而手动实现和使用 sys.stdout.write() 则更灵活,可以根据需求进行定制。

python随机数函数random,详解python随机数函数random,Python random.random(生成随机浮点数)函数的使用方法(图文详解)

Linux报 “disk quota exceeded” 异常的原因以及解决办法(图文详解)

 

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝