Python如何在多下载中使用线程处理

问题描述 投票:1回答:1

我现在使用threading进行并行下载,我有一个url_list img_list,我想以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()
python python-requests
1个回答
0
投票

在此行

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

您调用download_1(...)并将结果(空)传递给线程。这什么也没做。相反,您想分别传递download_1函数和参数。像这样:

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

在两个地方都做。

旁注:您应该t.join()最后两个线程。

© www.soinside.com 2019 - 2024. All rights reserved.