Python實(shí)現(xiàn)多線程下載腳本的示例代碼
0x01 分析
一個(gè)簡(jiǎn)單的多線程下載資源的Python腳本,主要實(shí)現(xiàn)部分包含兩個(gè)類:
Download類:包含download()和get_complete_rate()兩種方法。
- download()方法種首先用 urlopen() 方法打開(kāi)遠(yuǎn)程資源并通過(guò) Content-Length獲取資源的大小,然后計(jì)算每個(gè)線程應(yīng)該下載網(wǎng)絡(luò)資源的大小及對(duì)應(yīng)部分嗎,最后依次創(chuàng)建并啟動(dòng)多個(gè)線程來(lái)下載網(wǎng)絡(luò)資源的指定部分。
- get_complete_rate()則是用來(lái)返回已下載的部分占全部資源大小的比例,用來(lái)回顯進(jìn)度。
ThreadDownload類:該線程類繼承了threading.Thread類,包含了一個(gè)run()方法。
run()方法主要負(fù)責(zé)每個(gè)線程讀取網(wǎng)絡(luò)數(shù)據(jù)并寫(xiě)入本地。
0x02 代碼
# 文件名:ThreadDownload.py
import threading
from urllib.request import *
class Download:
def __init__(self, link, file_path, thread_num):
# 下載路徑
self.link = link
# 保存位置
self.file_path = file_path
# 使用多少線程
self.thread_num = thread_num
# 初始化threads數(shù)組
self.threads = []
def download(self):
req = Request(url=self.link, method='GET')
req.add_header('Accept', '*/*')
req.add_header('Charset', 'UTF-8')
req.add_header('Connection', 'Keep-Alive')
f = urlopen(req)
# 獲取要下載的文件的大小
self.file_size = int(dict(f.headers).get('Content-Length', 0))
f.close()
# 計(jì)算每個(gè)線程要下載的資源的大小
current_part_size = self.file_size // self.thread_num + 1
for i in range(self.thread_num):
# 計(jì)算每個(gè)線程下載的開(kāi)始位置
start_pos = i * current_part_size
# 每個(gè)線程使用一個(gè)wb模式打開(kāi)的文件進(jìn)行下載
t = open(self.file_path, 'wb')
t.seek(start_pos, 0)
# 創(chuàng)建下載線程
td = ThreadDownload(self.link, start_pos, current_part_size, t)
self.threads.append(td)
td.start()
# 獲下載的完成百分比
def get_complete_rate(self):
sum_size = 0
for i in range(self.thread_num):
sum_size += self.threads[i].length
return sum_size / self.file_size
class ThreadDownload(threading.Thread):
def __init__(self, link, start_pos, current_part_size, current_part):
super().__init__()
# 下載路徑
self.link = link
# 當(dāng)前線程的下載位置
self.start_pos = start_pos
# 定義當(dāng)前線程負(fù)責(zé)下載的文件大小
self.current_part_size = current_part_size
# 當(dāng)前文件需要下載的文件快
self.current_part = current_part
# 定義該線程已經(jīng)下載的字節(jié)數(shù)
self.length = 0
def run(self):
req = Request(url = self.link, method='GET')
req.add_header('Accept', '*/*')
req.add_header('Charset', 'UTF-8')
req.add_header('Connection', 'Keep-Alive')
f = urlopen(req)
# 跳過(guò)self.start_pos個(gè)字節(jié),表明該線程只負(fù)責(zé)下載自己負(fù)責(zé)的那部分內(nèi)容
for i in range(self.start_pos):
f.read(1)
# 讀取網(wǎng)絡(luò)數(shù)據(jù),并寫(xiě)入本地
while self.length < self.current_part_size:
data = f.read(1024)
if data is None or len(data) <= 0:
break
self.current_part.write(data)
# 累計(jì)該線程下載的總大小
self.length += len(data)
self.current_part.close()
f.close()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 文件名:thread_download-master.py
import sys
import time
from ThreadDownload import *
def show_process(dl):
while dl.get_complete_rate() < 1:
complete_rate = int(dl.get_complete_rate()*100)
print('\r' + '下載中···(已下載' + str(complete_rate) + '%)', end='', flush=True)
time.sleep(0.01)
def main():
try:
Link = input('[+]' + 'Link: ')
file_path = input('[+]' + 'File Path: ')
thread_number = input('[+]' + 'Thread Number: ')
thread_number = int(thread_number)
dl = Download(Link, file_path, thread_number)
dl.download()
print('\n開(kāi)始下載!')
show_process(dl)
print('\r' + '下載中···(已下載' + '100%)', end='', flush=True)
print('\n下載完成!')
except Exception:
print('Parameter Setting Error')
sys.exit(1)
if __name__=='__main__':
main()
0x03 運(yùn)行結(jié)果
下載歌曲《男孩》為例,下載到./Download/目錄下并命名為男孩.mp3,設(shè)置5個(gè)線程:


下載成功:

到此這篇關(guān)于Python實(shí)現(xiàn)多線程下載腳本的示例代碼的文章就介紹到這了,更多相關(guān)Python 多線程下載腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python模擬點(diǎn)擊在ios中實(shí)現(xiàn)的實(shí)例講解
在本篇文章里小編給大家整理的是一篇關(guān)于python模擬點(diǎn)擊在ios中實(shí)現(xiàn)的實(shí)例講解內(nèi)容,有需要的朋友們可以參考下。2020-11-11
一個(gè)小示例告訴你Python語(yǔ)言的優(yōu)雅之處
本篇中, 我們展示一下一段非常小的代碼, 這段代碼十分吸引我們, 因?yàn)樗褂檬謨?yōu)雅和直接的方式解決了一個(gè)常見(jiàn)的問(wèn)題.2014-07-07
解決Python spyder顯示不全df列和行的問(wèn)題
這篇文章主要介紹了解決Python spyder顯示不全df列和行的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04
使用Python防止SQL注入攻擊的實(shí)現(xiàn)示例
這篇文章主要介紹了使用Python防止SQL注入攻擊的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Python轉(zhuǎn)換itertools.chain對(duì)象為數(shù)組的方法
這篇文章主要介紹了Python轉(zhuǎn)換itertools.chain對(duì)象為數(shù)組的方法,通過(guò)代碼給大家介紹了itertools 的 chain() 方法,需要的朋友可以參考下2020-02-02

