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

2024-09-30 16:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用threading进行并行下载,现在我有一个url_列表img_list我想在两个线程中下载它,以便定义两个下载

我把一半放在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()

Tags: in脚本imgforlendownloaddefrequests
2条回答

在这一行

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()两个线程

您正在创建线程时调用这两个函数。因此,线程被传递为null,因此不执行任何操作。您应该像这样更改代码:

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

thread_1.start()
thread_2.start()

相关问题 更多 >