python 併發下載器實現方法示例
阿新 • • 發佈:2020-01-09
本文例項講述了python 併發下載器實現方法。分享給大家供大家參考,具體如下:
併發下載器
併發下載原理
from gevent import monkey import gevent import urllib.request # 有耗時操作時需要 monkey.patch_all() def my_downLoad(url): print('GET: %s' % url) resp = urllib.request.urlopen(url) data = resp.read() print('%d bytes received from %s.' % (len(data),url)) gevent.joinall([ gevent.spawn(my_downLoad,'http://www.baidu.com/'),gevent.spawn(my_downLoad,'http://www.itcast.cn/'),'http://www.itheima.com/'),])
執行結果
GET: http://www.baidu.com/
GET: http://www.itcast.cn/
GET: http://www.itheima.com/
111327 bytes received from http://www.baidu.com/.
172054 bytes received from http://www.itheima.com/.
215035 bytes received from http://www.itcast.cn/.
從上能夠看到是先發送的獲取baidu的相關資訊,然後依次是itcast、itheima,但是收到資料的先後順序不一定與傳送順序相同,這也就體現出了非同步,即不確定什麼時候會收到資料,順序不一定
實現多個視訊下載
from gevent import monkey import gevent import urllib.request #有IO才做時需要這一句 monkey.patch_all() def my_downLoad(file_name,url): print('GET: %s' % url) resp = urllib.request.urlopen(url) data = resp.read() with open(file_name,"wb") as f: f.write(data) print('%d bytes received from %s.' % (len(data),"1.mp4",'http://oo52bgdsl.bkt.clouddn.com/05day-08-%E3%80%90%E7%90%86%E8%A7%A3%E3%80%91%E5%87%BD%E6%95%B0%E4%BD%BF%E7%94%A8%E6%80%BB%E7%BB%93%EF%BC%88%E4%B8%80%EF%BC%89.mp4'),"2.mp4",'http://oo52bgdsl.bkt.clouddn.com/05day-03-%E3%80%90%E6%8E%8C%E6%8F%A1%E3%80%91%E6%97%A0%E5%8F%82%E6%95%B0%E6%97%A0%E8%BF%94%E5%9B%9E%E5%80%BC%E5%87%BD%E6%95%B0%E7%9A%84%E5%AE%9A%E4%B9%89%E3%80%81%E8%B0%83%E7%94%A8%28%E4%B8%8B%29.mp4'),])
上面的url可以換為自己需要下載視訊、音樂、圖片等網址
更多關於Python相關內容可檢視本站專題:《Python Socket程式設計技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》
希望本文所述對大家Python程式設計有所幫助。