python pyqt5 计算下载文件的进度百分比
思路
- 从远程服务器获取文件大小
- 每次只下载固定大小
- 下载次数 × 固定大小 = 已下载大小
- 已下载大小 ➗ 文件大小 * 100 即为下载进度百分比
代码
python
import subprocess
import requests
from contextlib import closing
# 下载文件
r = requests.get("https://***.com/_latest.exe",stream=True)
with closing(r) as response:
# 每次下载的大小
chunk_size = 1024
# 文件总大小
content_size = int(response.headers['content-length'])
# 下载次数
data_count = 0
# 下载数据写入文件
with open('_latest.exe','wb') as file:
for data in response.iter_content(chunk_size=chunk_size):
file.write(data)
data_count = data_count + len(data)
# 进度
now_jd = (data_count / content_size) * 100
print(f'文件已下载:({data_count}字节/{content_size}字节) {round(now_jd, 2)}%')
# 下载完成后打开
subprocess.call(['_latest.exe'])