python - Python如何在多下载中使用线程
问题描述
我threading
习惯于进行并行下载,现在我有一个 url_listimg_list
我想在 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()
在最后两个线程。
推荐阅读
- html - RTL 中的星级评定系统
- jmeter - 无法从 Jmeter 中的 2 个 CSF 文件中获取数据
- powershell - 通过 Powershell 通过 Azure Key Vault 管理的密钥访问 Azure 存储
- java - Java 在 HashMap 中存储连接
- angular - 如果没有 redux devtools 扩展,带有 NgRx 的 Angular 应用程序无法正常工作
- macos - 在一个文件夹中创建多个空的 .txt 文件
- c++ - 如何在 C++ 中调用命令行工具
- reactjs - 如何从打字稿中的反应钩子组件发出偶数?
- flutter - ffmpeg 似乎输出带有错误编解码器的视频?
- javascript - 在 if/else (Javascript) 中重新分配变量