目录

Python3.6.8 + tqdm

tqdm在阿拉伯语意为"进步"的意思,是一个快速、扩展性强的进度条工具库,只需要封装任意的tqdm(iterable)即可,特点:

  • tqdm有较小的开销,智能预测剩余时间和不必要的迭代显示。
  • tqdm使用与任何平台:Linux、windows、Mac、FreeBSD、NetBSD、Solaris/SunOS,可以是任何控制台或GUI,并且较好的支持Ipython和Jupyter
  • tqdm需要任何依赖,只要下载就可以了

install

pip install tqdm

usage

基本用法

# 基本用法: tqdm.tqdm
import time
import tqdm

for i in tqdm.tqdm(range(1000)):
    time.sleep(0.01)

# 也可以这样
for i in tqdm.trange(100):
    time.sleep(0.1)
    pass

Python - tqdm

使用with语句对tqdm进行手动控制

import time
import tqdm

total = 100
with tqdm.tqdm(total=total) as bar:
    for i in range(total):
        time.sleep(0.01)
        bar.update(1)  # 每次更新进度条的长度

Python - tqdm

应用于文件传输中

import os
import tqdm

send_size = 0
file_name = "a.mp4"
file_size = os.stat(file_name).st_size
t = tqdm.tqdm(total=file_size, desc='下载进度')
with open(file_name, 'rb') as f:
    while send_size < file_size:
        if file_size - send_size < 1024:
            total_data = f.read(file_size - send_size)
        else:
            total_data = f.read(1024)
        send_size += len(total_data)
        t.update(len(total_data))
t.close()  # 最后不要忘记close

Python - tqdm

结合requests使用,下载视频

#!/bin/bash
# -*- coding: utf-8 -*-

import requests
from tqdm import tqdm


def download():
    file_path = 'a.mp4'
    url = 'https://video.pearvideo.com/mp4/adshort/20210105/cont-1715025-15561875_adpkg-ad_hd.mp4'
    with open(file_path, 'wb') as f:
        response = requests.get(url=url, stream=True)
        content_size = int(response.headers['Content-Length']) / 1024  # 将字节单位转为 kb
        for chunk in tqdm(iterable=response.iter_content(1024), total=content_size, unit='k', desc='downloading'):
            f.write(chunk)
        print('{} download done.....'.format(file_path))


if __name__ == '__main__':
    download()

Python - tqdm


that's all, see also:

详细介绍Python进度条tqdm的使用 | 使用tqdm实现下载文件进度条

分类:

技术点:

相关文章: