python 多线程下载
时间: 2023-11-11 09:00:55 浏览: 139
好的,针对你的问题,我可以给出以下的代码示例:
```python
import requests
import threading
def download(url, start_pos, end_pos, file):
headers = {'Range': 'bytes=%d-%d' % (start_pos, end_pos)}
res = requests.get(url, headers=headers)
file.seek(start_pos)
file.write(res.content)
def multi_thread_download(url, num_thread=8):
res = requests.head(url)
file_name = url.split('/')[-1]
file_size = int(res.headers['Content-Length'])
part = file_size // num_thread
file = open(file_name, 'wb')
threads = []
for i in range(num_thread):
start_pos = i * part
if i == num_thread - 1:
end_pos = file_size
else:
end_pos = start_pos + part - 1
t = threading.Thread(target=download, args=(url, start_pos, end_pos, file))
threads.append(t)
t.start()
for t in threads:
t.join()
file.close()
multi_thread_download('http://example.com/example.zip', num_thread=8)
```
这个代码示例实现了一个多线程下载文件的功能。首先通过 `requests.head` 方法获取文件大小,然后根据线程数将文件分成若干个部分,每个线程下载一个部分。最后将所有部分合并成一个完整的文件。
阅读全文