首先,请确保已经安装了`tqdm`库,它是一个用于生成命令行进度条的强大工具。如果尚未安装可以使用pip来快速添加:
bash
pip install tqdm
然后我们可以结合requests或者其他HTTP客户端库以及`tqdm`以流式读写的方式来实现实时更新的下载进度:
python
import requests
from tqdm import tqdm
def download_file(url, filename):
# 初始化请求对象,并设定stream=True以便于分块读取响应内容
response = requests.get(url, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
total_length = int(response.headers['content-length'])
# 如果服务端返回Content-Length,则可精确计算百分比;否则只能估算
if total_length is not None:
progress_bar = tqdm(total=total_length)
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
progress_bar.update(len(chunk))
else:
print("无法确定总长度,将以未知大小的方式下载...")
progress_bar = tqdm(unit='B', unit_scale=True)
for chunk in response.iter_content(8196):
f.write(chunk)
progress_bar.update len(chunk))
progress_bar.close()
return True
else:
raise Exception(f"错误:{response.status_code} - {url}")
# 使用示例:
download_url = "http://example.com/largefile.zip"
local_path = "./largefile.zip"
if __name__ == "__main__":
download_file(download_url, local_path)
上述代码中,我们通过`requests.get()`函数发送GET请求到指定URL,并设置参数 `stream=True` 来允许我们在接收整个响应体之前就开始处理其内容(即“边下边存”)。接着开启一个新的二进制模式打开本地文件准备存储接收到的数据。
对于已知总体积的情况,我们创建了一个基于总量的内容长度(`'content-length'`) 的`tqdm`实例作为进度条,每次迭代过程中调用`.update()`方法增加当前传输量对应的进程值。
而对于未提供具体尺寸的服务端响应情况,我们将采用无界进度条 (`unit_scale=True`) ,仅表示操作仍在继续而不能准确指示完成度。
总之,借助Python标准库和第三方模块如requests与tqdm的合作,为我们的文件下载过程提供了清晰且实用的状态反馈机制,使得用户能直观地了解下载进度及剩余时间等关键信息,极大地提高了程序的人性化程度及其运行可视化表现。