【问题标题】:How to download a file over HTTP with multi-thread (asynchronous download) using Python 2.7如何使用 Python 2.7 通过 HTTP 多线程(异步下载)下载文件
【发布时间】:2015-11-05 10:18:07
【问题描述】:

我有一个文件要下载(从 json 中提取的下载路径。例如:http://testsite/abc.zip)。

我需要帮助来执行,所有 5 个线程都应该将 abc.zip 文件下载到输出目录,并且下载必须是异步并发

目前使用以下代码,它确实会下载文件 5 次,但它会逐一下载(同步)。

我想要的是同步下载。

def dldr(file=file_url, outputdir=out1):
    local_fn = str(uuid.uuid4())
    if not os.path.exists(outputdir):
        os.makedirs(outputdir)
    s = datetime.now()
    urllib.urlretrieve(file, outputdir + os.sep + local_fn)
    e = datetime.now()
    time_diff = e - s
    logger(out1, local_fn, time_diff)

for i in range(1, 6):
    t = threading.Thread(target=dldr())
    t.start()

我已阅读 Requests with multiple connections 的帖子,它很有帮助,但没有解决所提问题的要求。

【问题讨论】:

标签: python multithreading python-2.7 http


【解决方案1】:

我使用线程模块来下载线程:
也有请求,不过你可以自己改成urllib。

import threading
import requests

def download(link, filelocation):
    r = requests.get(link, stream=True)
    with open(filelocation, 'wb') as f:
        for chunk in r.iter_content(1024):
            if chunk:
                f.write(chunk)

def createNewDownloadThread(link, filelocation):
    download_thread = threading.Thread(target=download, args=(link,filelocation))
    download_thread.start()

for i in range(0,5):
    file = "C:\\test" + str(i) + ".png"
    print file
    createNewDownloadThread("http://stackoverflow.com/users/flair/2374517.png", file)

【讨论】:

  • 为什么我们应该分块下载而不是 f.write(r.content)?
  • @GarfieldCat,因为不使用块下载会将整个文件读入内存,这将导致非常大的文件出现内存问题(想想> 1Gb)。对于一个块,每次只有“块”被读入内存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多