python requests 展示下载进度

335 阅读1分钟

结合tqdm包使用。

tqdm包的用法

安装

pip install tqdm

简单使用 :引入tqdm方法,然后使用将可迭代(iterable)的对象传入tqdm()方法即可。

with tqdm(total=100) as pbar:#tqdm方法设置进度条长度
    for i in range(10):
        sleep(0.1)
        pbar.update(10)#手动更新进度

结合requests使用

步骤如下:

  1. 获取Header中的Content-length字段得到文件大小
  2. 初始化tqdm
  3. 分块读取文件并更新进度条
def download_url_new(url, file_path, chunk_size):
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        file_size = r.headers['Content-length']
        # pbar = tqdm(total=int(file_size), unit='B', unit_scale=True, desc=file_path)
        with tqdm(total=int(file_size), unit='B', unit_scale=True, desc=file_path) as pbar:
            with open(file_path, 'wb') as f:
                for chunk in r.iter_content(chunk_size=chunk_size):
                    f.write(chunk)
                    pbar.update(chunk_size)

将tqdm.tqdm进度条输出传输到logger

上面的例子,进度条将会输出到std,如果想要把结果输出到logger文件中,应该怎么做?

主要是用到了tqdm的函数的file参数。我们先看下file参数表示什么。

file  : `io.TextIOWrapper后者` or `io.StringIO`, optional
    Specifies where to output the progress messages
    (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
    methods.  For encoding, see `write_bytes`.

io.TextIOWrapper或者io.TextIOWrapper,默认是sys.stderr。

代码示例:

import io
import logging
from backup import logger

class TqdmToLogger(io.StringIO):
    """
        Output stream for TQDM which will output to logger module instead of
        the StdOut.
    """

    def __init__(self, logger):
        super(TqdmToLogger, self).__init__()
        self.logger = logger

    def write(self, buf):
        self.buf = buf.strip('\r\n\t ')

    def flush(self):
        self.logger.log(logging.INFO, self.buf)


def download_url_new(url, file_path, chunk_size):
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        file_size = r.headers['Content-length']
        # pbar = tqdm(total=int(file_size), unit='B', unit_scale=True, desc=file_path)
        tqdm_logger = TqdmToLogger(logger)
        with tqdm(total=int(file_size), unit='B', unit_scale=True, desc=file_path, file=tqdm_logger) as pbar:
            with open(file_path, 'wb') as f:
                for chunk in r.iter_content(chunk_size=chunk_size):
                    f.write(chunk)
                    pbar.update(chunk_size)

参考:github.com/tqdm/tqdm/i…