python 并發(fā)下載器實現(xiàn)方法示例
本文實例講述了python 并發(fā)下載器實現(xiàn)方法。分享給大家供大家參考,具體如下:
并發(fā)下載器
并發(fā)下載原理
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/'), gevent.spawn(my_downLoad, '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/.
從上能夠看到是先發(fā)送的獲取baidu的相關信息,然后依次是itcast、itheima,但是收到數(shù)據(jù)的先后順序不一定與發(fā)送順序相同,這也就體現(xiàn)出了異步,即不確定什么時候會收到數(shù)據(jù),順序不一定
實現(xiàn)多個視頻下載
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), url)) gevent.joinall([ gevent.spawn(my_downLoad, "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'), gevent.spawn(my_downLoad, "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可以換為自己需要下載視頻、音樂、圖片等網(wǎng)址
更多關于Python相關內(nèi)容可查看本站專題:《Python Socket編程技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
- python基于gevent實現(xiàn)并發(fā)下載器代碼實例
- python實現(xiàn)可以斷點續(xù)傳和并發(fā)的ftp程序
- Python多進程并發(fā)(multiprocessing)用法實例詳解
- Python控制多進程與多線程并發(fā)數(shù)總結
- python實現(xiàn)多線程的方式及多條命令并發(fā)執(zhí)行
- python并發(fā)編程之多進程、多線程、異步和協(xié)程詳解
- python監(jiān)控網(wǎng)站運行異常并發(fā)送郵件的方法
- Python實現(xiàn)多并發(fā)訪問網(wǎng)站功能示例
- 實例探究Python以并發(fā)方式編寫高性能端口掃描器的方法
- Python socket實現(xiàn)的文件下載器功能示例
- python使用urllib模塊開發(fā)的多線程豆瓣小站mp3下載器
相關文章
python 讀取dicom文件,生成info.txt和raw文件的方法
今天小編就為大家分享一篇python 讀取dicom文件,生成info.txt和raw文件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python數(shù)據(jù)分析應用之Matplotlib數(shù)據(jù)可視化詳情
這篇文章主要介紹了Python數(shù)據(jù)分析應用之Matplotlib數(shù)據(jù)可視化詳情,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06Python實現(xiàn)的插入排序算法原理與用法實例分析
這篇文章主要介紹了Python實現(xiàn)的插入排序算法原理與用法,簡單描述了插入排序的原理,并結合實例形式分析了Python實現(xiàn)插入排序的相關操作技巧,需要的朋友可以參考下2017-11-11