【问题标题】:How to accelerate download speed of a file using Python?如何使用 Python 加快文件的下载速度?
【发布时间】:2019-06-15 15:38:46
【问题描述】:

我正在尝试使用wb 模式通过write 函数下载位于网络上的文件。与通过网络浏览器下载的速度相比,文件下载速度太慢(因为我有高速互联网连接)。如何加快下载速度?有没有更好的处理文件下载的方法?

这是我的使用方式:

resp = session.get(download_url)
with open(package_name + '.apk', 'wb+') as local_file:
    local_file.write(resp.content)

我实验过requests和urllib3库的下载速度几乎一样。下面是下载15 MB文件的实验结果:

  • requests: 0:02:00.689587
  • urllib3: 0:02:05.833442

附言我的 Python 版本是3.7.0,我的操作系统是Windows 10 version 1903。

附言我调查了reportedly similar question,但答案/cmets 不起作用。

【问题讨论】:

标签: python python-3.x python-requests urllib3


【解决方案1】:

看起来很奇怪,但很有道理——浏览器会缓存下载,而直接写入文件则不会。

考虑:

from tempfile import SpooledTemporaryFile
temp = SpooledTemporaryFile()
resp = session.get(download_url)
temp.write(resp.content)
temp.seek(0)
with open(package_name + '.apk', 'wb') as local_file:
    local_file.write(resp.content)

那可能会更快。

如果你可以创建一个异步写入本地文件,你就不会耽误你的程序。

  import asyncio
  async def write_to_local_file(name, spool_file):
      spool_file.seek(0)
      with open(package_name + '.apk', 'wb') as local_file:
          local_file.write(spool_file.read())

然后:

from tempfile import SpooledTemporaryFile
temp = SpooledTemporaryFile()
resp = session.get(download_url)
temp.write(resp.content)
asyncio.run(write_to_local_file("my_package_name", temp))

【讨论】:

  • 在导入SpooledTemporaryFile 和asyncio 后执行脚本时得到ModuleNotFoundError: No module named '_contextvars'。
  • @talha06 我在 Mac 上使用 python 3.7,你使用的是什么版本的 python 什么操作系统?您可以尝试从 python shell 中的每个导入吗?
  • 我的操作系统是Windows 10 (version 1903),Python 的版本是3.7.0,正如我在OP 中声明的那样。
  • @talha06 :是的,contextvars 和 Windows 似乎存在一个已知错误。我想知道没有 asyncio 的代码是否相当快?假脱机临时文件应该会有所帮助。
  • 不,很遗憾,我还没有发现任何具体的加速。
猜你喜欢
  • 2015-03-28
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 2013-01-01
相关资源
最近更新 更多