マルチダウンロードにスレッドを使用する方法のPython

M_Sea:

私は使用はしていますthreading今私が持っているurl_list並列ダウンロードを行うにはimg_list、私はそうDEF 2件のダウンロード2スレッドでそれをダウンロードしたいの。

私はに半分を入れdownload1にし、半分download2それが完了するまでにスピードアップしますので、私はまだシリアルでスクリプト私のダウンロードを実行したときに最後に、私はどのように私は私のスクリプトを変更することができ、なぜ分からないのですか?

ここでのコードは次のとおりです。

import requests,threading
img_list=[...]
num=len(img_list)
def download_1(img_list):
    n=0
    for i in img_list:
        n+=1
        with open('./img/'+str(n)+'.jpg','wb')as f:
            f.write(requests.get(i).content)
            print(str(n)+"download1 complete")
def download_2(img_list):
    n=len(img_list)
    for i in img_list:
        n+=1
        with open('./img/'+str(n)+'.jpg','wb')as f:
            f.write(requests.get(i).content)
            print(str(n)+"download2 complete")
thread_1 = threading.Thread(target=download_1(img_list[:int(num/2)]))
thread_2 = threading.Thread(target=download_2(img_list[int(num/2):]))
thread_1.start()
thread_2.start()
気まぐれ:

この行で

threading.Thread(target=download_1(img_list[:int(num/2)]))

あなたは、呼び出しdownload_1(...)スレッドに(null)をし、その結果を渡します。それは逐次実行される理由です。代わりに、渡したいdownload_1スレッドに関数自体(ではない、それを呼び出した結果を)。このような:

threading.Thread(target=download_1, args=(img_list[:int(num/2)],))

両方の場所でそれを行います。

サイドノート:あなたがすべきt.join()最後に両方のスレッドを。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=373088&siteId=1