2015-11-05 130 views
2

我有一个要下载的文件(从json提取的下载路径。eg: http://testsite/abc.zip)。如何使用Python 2.7多线程(异步下载)通过Http下载文件

我需要帮助来执行,所有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帖子,它有帮助,但没有解决问题的要求。

+1

那么你的问题是什么? – user2266449

+0

上面的代码将文件下载到某个位置。如何在这里实现多线程同时由5个代理下载文件? –

+0

哦,你想单个文件下载多线程: 比它是重复的问题:http://stackoverflow.com/questions/9701682/download-a-single-file-using-multiple-threads – cvakiitho

回答

3

我使用线程模块下载线程: 也请求,但你可以自己更改为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)