我们需要用python 写一个多线程的下载器

我们要先获取这个文件的大小 然后将其分片 然后启动多线程 分别去下载 然后将其拼接起来

#!/usr/bin/env python
#coding:utf-8
import requests from multiprocessing.dummy import Pool as ThreadPool class my_download(object): def __init__(self,URL):
self.url = URL
self.thread_num = 5
self.file_nume = URL.split('/')[-1]
url_headers = requests.head(self.url)
self.total = int(url_headers.headers['Content-Length'])
print self.total
#print type('total is %s' % (self.total)) def get_file_range(self):
ranges = [] download_num = int(self.total/self.thread_num)
print download_num
for i in range(self.thread_num):
if i == self.thread_num-1:
ranges.append((download_num*i,''))
else:
ranges.append((download_num*i,download_num*(i+1)))
return ranges def download_file(self,val):
f = open(self.file_nume, 'w')
r = requests.get(self.url, headers={'Range': 'Bytes=%s-%s' % val, 'Accept-Encoding': '*'})
f.seek(val[0])
f.write(r.content)
return f def run(self): file_list = self.get_file_range()
#print file_list
Pool = ThreadPool(4)
res = map(self.download_file,file_list) for i in res:
i.close() Pool.close()
Pool.join() url = "https://img3.doubanio.com/icon/up121443072-1.jpg"
downloader = my_download(url)
downloader.run()

最新文章

  1. iOS开发之ImageView复用实现图片无限轮播
  2. 利用python进行数据分析 (学习笔记)
  3. B+树索引和哈希索引的区别——我在想全文搜索引擎为啥不用hash索引而非得使用B+呢?
  4. cisco LAN
  5. javascript 返回数组中不重复的元素
  6. Keil的使用方法 - 常用功能(一)
  7. 考试宝典-真题园安卓AppV2.1.0新版发布啦,全新界面,全新体验,全面适配Android 5.0&6.0系统!
  8. php 需熟练掌握的几个函数
  9. PsExec.exe执行远程程序
  10. 技巧收集-W1701
  11. js如何获取隐藏的元素的高度
  12. 暖春许愿季丨i春秋给你送福利
  13. SQL反模式学习笔记7 多态关联
  14. VC中的字符串转换宏
  15. 4S店的潜规则内幕曝光
  16. Codeforces822 B. Crossword solving
  17. canvas 实现签名效果
  18. main函数的参数argc和argv
  19. html5 ajax 文件上传
  20. 微信小程序及开发工具介绍

热门文章

  1. 织梦DEDECMS会员中心发布文章修改提示"数据校验不对,程序返回"
  2. js插件设置innerHTML时,在IE8下报错“未知运行时错误”
  3. [dp uestc oj] G - 邱老师玩游戏
  4. 【转】 树莓派初次启动攻略for Mac
  5. 解决 cocos2dx iOS/mac 设置纹理寻址模式后纹理变黑的问题
  6. Vue路由跳转到新页面时 默认在页面最底部 而不是最顶部 的解决
  7. 51nod——2489 小b和灯泡(打表/平方数)
  8. NOIP模拟赛 抓牛
  9. 01 Web框架介绍
  10. 移动端H5前端性能优化指南: