python 并发下载器实现方法示例

yipeiwu_com6年前Python基础

本文实例讲述了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/'),
    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/.

从上能够看到是先发送的获取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), 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可以换为自己需要下载视频、音乐、图片等网址

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python基于socket进行端口转发实现后门隐藏的示例

思想: 用户正常浏览器访问请求通过8080端口,请求若为http请求,则正常转发到80端口保证网站正常运行。否则转发到8888端口执行系统命令。 8888端口监听代码: #!/usr...

python 实现提取某个索引中某个时间段的数据方法

如下所示: from elasticsearch import Elasticsearch import datetime import time import dateutil.p...

python操作mysql代码总结

安装模块 windows:pip install pymysql ubuntu:sudo pip3 install pymysql python操作mysql步骤 import pym...

Python Tkinter实现简易计算器功能

Python Tkinter实现简易计算器功能

闲暇时间用tkinter写了个简易计算器,可实现简单的加减乘除运算,用了Button和Entry2个控件,下面是代码,只是简单的用了偏函数partial,因为那么多button的大部分参...

Python cookbook(数据结构与算法)找到最大或最小的N个元素实现方法示例

本文实例讲述了python找到最大或最小的N个元素实现方法。分享给大家供大家参考,具体如下: 问题:想在某个集合中找出最大或最小的N个元素 解决方案:heapq模块中的nlargest(...