Python實(shí)現(xiàn)多線程下載腳本的示例代碼
0x01 分析
一個簡單的多線程下載資源的Python腳本,主要實(shí)現(xiàn)部分包含兩個類:
Download類:包含download()和get_complete_rate()兩種方法。
download()方法種首先用 urlopen() 方法打開遠(yuǎn)程資源并通過 Content-Length獲取資源的大小,然后計(jì)算每個線程應(yīng)該下載網(wǎng)絡(luò)資源的大小及對應(yīng)部分嗎,最后依次創(chuàng)建并啟動多個線程來下載網(wǎng)絡(luò)資源的指定部分。 get_complete_rate()則是用來返回已下載的部分占全部資源大小的比例,用來回顯進(jìn)度。ThreadDownload類:該線程類繼承了threading.Thread類,包含了一個run()方法。
run()方法主要負(fù)責(zé)每個線程讀取網(wǎng)絡(luò)數(shù)據(jù)并寫入本地。
0x02 代碼
# 文件名:ThreadDownload.pyimport threadingfrom 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ì)算每個線程要下載的資源的大小 current_part_size = self.file_size // self.thread_num + 1 for i in range(self.thread_num): # 計(jì)算每個線程下載的開始位置 start_pos = i * current_part_size # 每個線程使用一個wb模式打開的文件進(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_sizeclass 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) # 跳過self.start_pos個字節(jié),表明該線程只負(fù)責(zé)下載自己負(fù)責(zé)的那部分內(nèi)容 for i in range(self.start_pos): f.read(1) # 讀取網(wǎng)絡(luò)數(shù)據(jù),并寫入本地 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.pyimport sysimport timefrom 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開始下載!’) 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個線程:
下載成功:
到此這篇關(guān)于Python實(shí)現(xiàn)多線程下載腳本的示例代碼的文章就介紹到這了,更多相關(guān)Python 多線程下載腳本內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. docker compose idea CreateProcess error=2 系統(tǒng)找不到指定的文件的問題2. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實(shí)現(xiàn)方法3. 一文秒懂idea的git插件跟翻譯插件4. python爬蟲利用代理池更換IP的方法步驟5. layui Ajax請求給下拉框賦值的實(shí)例6. Java反射技術(shù)原理與用法實(shí)例分析7. python中pandas.read_csv()函數(shù)的深入講解8. PHP設(shè)計(jì)模式之迭代器模式Iterator實(shí)例分析【對象行為型】9. JS中的常見數(shù)組遍歷案例詳解(forEach, map, filter, sort, reduce, every)10. Python語言規(guī)范之Pylint的詳細(xì)用法
