python使用线程池保存图片
时间: 2023-12-22 20:28:23 浏览: 173
以下是使用Python线程池保存图片的示例代码:
```python
import requests
from concurrent.futures import ThreadPoolExecutor
def download_image(url):
response = requests.get(url)
filename = url.split("/")[-1]
with open(filename, "wb") as f:
f.write(response.content)
print(f"{filename} saved successfully.")
def save_images_with_threadpool(urls, max_workers):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
executor.map(download_image, urls)
# 示例
urls = ["https://example.com/image1.jpg", "https://example.com/image2.jpg", "https://example.com/image3.jpg"]
save_images_with_threadpool(urls, 10)
```
在这个示例中,我们使用了Python的requests库来下载图片,并使用了concurrent.futures模块中的ThreadPoolExecutor来创建线程池。download_image函数用于下载单个图片,save_images_with_threadpool函数用于将多个图片的下载任务提交给线程池。在示例中,我们将线程池的最大工作线程数设置为10。
阅读全文