python基于gevent实现并发下载器代码实例
这篇文章主要介绍了python基于gevent实现并发下载器代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
并发下载原理
import gevent from gevent import monkey 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, "https://www.baidu.com"), gevent.spawn(my_download, "https://www.cnblogs.com"), gevent.spawn(my_download, "https://www.huya.com") ])
运行结果:
GET: https://www.baidu.com GET: https://www.cnblogs.com GET: https://www.huya.com 227 bytes received from https://www.baidu.com. 46411 bytes received from https://www.cnblogs.com. 353563 bytes received from https://www.huya.com.
实现多张图片同时下载
import gevent from gevent import monkey import urllib.request monkey.patch_all() def my_download(url, image_path): print('GET: %s' % url) resp = urllib.request.urlopen(url) data = resp.read() print('%d bytes received from %s.' % (len(data), url)) with open(image_path, "wb") as f: f.write(data) gevent.joinall([ gevent.spawn(my_download, "https://cache..com/upload/information/20200622/113/20690.jpg", "1.jpg"), gevent.spawn(my_download, "https://cache..com/upload/information/20200622/113/20691.jpg", "2.jpg"), gevent.spawn(my_download, "https://cache..com/upload/information/20200622/113/20692.jpg", "3.jpg"), ])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。