You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python从云存储桶下载Zip文件时显示进度条

给GCS下载Zip文件添加进度条的实现方法

嘿,这个需求太实用了!要给Google Cloud Storage(GCS)的文件下载过程加上进度条,我们有两种很靠谱的实现方式,看你偏好哪种:

方案一:用tqdm库快速实现(最省心)

tqdm是Python里专门做进度条的工具库,用法简单还美观。首先得先安装它:

pip install tqdm

然后修改你的代码,用blob.download_to_file()配合tqdm追踪进度——因为download_to_filename()是封装后的方法,直接用底层的download_to_file()更方便控制:

from tqdm import tqdm
# 这里导入你原本的storage_client相关模块
import storage

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)

# 获取文件总大小,用来计算进度比例
file_size = blob.size
print('Downloading file')

# 打开本地文件,用tqdm包装写入过程
with open(destination_file_name, 'wb') as f:
    with tqdm(total=file_size, unit='B', unit_scale=True, desc=source_blob_name) as pbar:
        # 定义回调函数,每次写入字节后更新进度条
        def progress_callback(bytes_written):
            pbar.update(bytes_written)
        
        blob.download_to_file(f, progress_callback=progress_callback)

print('Download completed')

这个方案的好处是不用自己写进度条逻辑,tqdm会帮你处理进度计算、动态刷新,还能自动切换显示单位(比如从KB到MB)。

方案二:手动实现进度条(无需额外依赖)

如果不想安装第三方库,我们也可以自己写一个轻量的进度条,用printflush参数实现动态更新:

# 导入你原本的storage_client相关模块
import storage

bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)

file_size = blob.size
downloaded_bytes = 0
print('Downloading file')

def progress_callback(bytes_written):
    nonlocal downloaded_bytes
    downloaded_bytes += bytes_written
    # 计算进度百分比,用50个字符的长度做进度条
    progress_percent = (downloaded_bytes / file_size) * 100
    bar_length = 50
    filled_length = int(bar_length * downloaded_bytes // file_size)
    bar = '=' * filled_length + '-' * (bar_length - filled_length)
    # 用\r让光标回到行首,实现覆盖打印
    print(f'\r[{bar}] {progress_percent:.1f}%', end='', flush=True)

with open(destination_file_name, 'wb') as f:
    blob.download_to_file(f, progress_callback=progress_callback)

# 下载完成后换行,避免和后续输出混在一起
print('\nDownload completed')

这个手动实现的进度条胜在轻量,不需要额外安装任何包,适合对依赖有严格要求的场景。

两种方案的核心都是利用download_to_file()progress_callback参数——每次有字节写入本地文件时,这个回调函数就会被触发,我们只需要在回调里更新进度显示就行。

内容的提问来源于stack exchange,提问作者Sam

火山引擎 最新活动