Python 进度条和下载 [英] Python progress bar and downloads
问题描述
我有一个 Python 脚本,可以启动一个可下载文件的 URL.有没有办法让 Python 显示下载进度而不是启动浏览器?
I have a Python script that launches a URL that is a downloadable file. Is there some way to have Python display the download progress as oppose to launching the browser?
推荐答案
我刚刚为此编写了一个超级简单(略显笨拙)的方法,用于从某个站点抓取 PDF.请注意,它只能在基于 Unix 的系统(Linux、mac os)上正常工作,因为 PowerShell 不处理 "\r"
:
I've just written a super simple (slightly hacky) approach to this for scraping PDFs off a certain site. Note, it only works correctly on Unix based systems (Linux, mac os) as PowerShell does not handle "\r"
:
import sys
import requests
link = "http://indy/abcde1245"
file_name = "download.data"
with open(file_name, "wb") as f:
print("Downloading %s" % file_name)
response = requests.get(link, stream=True)
total_length = response.headers.get('content-length')
if total_length is None: # no content length header
f.write(response.content)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) )
sys.stdout.flush()
它使用请求库,因此您需要安装它.这会在您的控制台中输出类似以下内容:
It uses the requests library so you'll need to install that. This outputs something like the following into your console:
>下载download.data
>Downloading download.data
>[============ ]
>[============= ]
脚本中的进度条有 52 个字符宽(2 个字符只是 []
,所以 50 个字符的进度).每个 =
代表下载量的 2%.
The progress bar is 52 characters wide in the script (2 characters are simply the []
so 50 characters of progress). Each =
represents 2% of the download.
这篇关于Python 进度条和下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!