首页 > 解决方案 > Python如何在多下载中使用线程

问题描述

threading习惯于进行并行下载,现在我有一个 url_listimg_list我想在 2 个线程中下载它,所以定义两个下载。

我将一半放入一半放入download1download2这样它会加快完成速度,但最后当我运行脚本时,我的下载仍然是串行的,我不知道为什么,我该如何修改我的脚本?

这是代码:

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()

标签: pythonpython-requests

解决方案


在这一行

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()在最后两个线程。


推荐阅读