2015-11-05 131 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)