在下载文件时使用Tqdm添加进度条
发布时间:2020-12-20 13:17:30 所属栏目:Python 来源:网络整理
导读:我一直在尝试使用 python 3.6中的Tqdm模块设置进度条,但似乎我已经到了一半. 我的代码如下: from tqdm import tqdmimport requestsimport timeurl = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'# Streamin
我一直在尝试使用
python 3.6中的Tqdm模块设置进度条,但似乎我已经到了一半.
我的代码如下: from tqdm import tqdm import requests import time url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf' # Streaming,so we can iterate over the response. r = requests.get(url,stream=True) #Using The Url as a filename local_filename = url.split('/')[-1] # Total size in bytes. total_size = int(r.headers.get('content-length',0)) #Printing Total size in Bytes print(total_size) #TQDM with open(local_filename,'wb') as f: for data in tqdm(r.iter_content(chunk_size = 512),total=total_size,unit='B',unit_scale=True): f.write(data) 问题是,当我在r.iter_content中插入chunk_size = 512时,进度条在显示下载数据时根本不加载,但是当我完全删除chunk_size = 512并且将括号留空时,条形加载就像它一样应该但下载速度太可怕了. 我在这做错了什么? 解决方法
你并不遥远,但只是遗漏了几乎所有的代码,以使进度条相应地工作.假设您已经创建了界面,这是我用于进度条的方法.它会下载文件并将其保存在桌面上(但您可以指定要保存的位置).它只需要下载文件的大小并将其除以总文件大小,然后使用该值来更新进度条.如果此代码有帮助,请告诉我:
url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf' save = 'C:/Users/' + username + "/Desktop/" r = requests.get(url,stream=True) total_size = int(r.headers["Content-Length"]) downloaded = 0 # keep track of size downloaded so far chunkSize = 1024 bars = int(fileSize / chunkSize) print(dict(num_bars=bars)) with open(filename,"wb") as f: for chunk in tqdm(r.iter_content(chunk_size=chunkSize),total=bars,unit="KB",desc=filename,leave=True): f.write(chunk) downloaded += chunkSize # increment the downloaded prog = ((downloaded * 100 / fileSize)) progress["value"] = (prog) # *100 #Default max value of tkinter progress is 100 return 进度=进度条 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |