python 多线程将大文件分开下载后在合并的实例

yipeiwu_com6年前Python基础

废话不多说了,上代码吧:

import threading
import requests
import time
import os


class Mythread(threading.Thread):
  def __init__(self,url,startpos,endpos,f):
    super(Mythread,self).__init__()
    self.url=url
    self.startpos=startpos
    self.endpos=endpos
    self.fd=f
  def download(self):
    print('start thread:%s at %s'%(self.getName(),time.time()))
    headers={'Range':'bytes=%s-%s'%(self.startpos,self.endpos)}
    res=requests.get(self.url,headers=headers)
    self.fd.seek(self.startpos)
    self.fd.write(res.content)
    print('Stop thread:%s at%s'%(self.getName(),time.time()))
    self.fd.close()
  def run(self):
    self.download()
if __name__=="__main__":
  url='http://www.wendangxiazai.com/word/b-cfbdc77931b765ce050814a9-1.doc'
  filename=url.split('/')[-1]
  filesize=int(requests.head(url).headers['Content-Length'])
  print('%s filesize:%s'%(filename,filesize))


  threadnum=3
  threading.BoundedSemaphore(threadnum)#允许线程个数
  step=filesize//threadnum
  mtd_list=[]
  start=0
  end=-1
  
  tempf = open('E:\Python\py\web'+filename,'w')
  tempf.close()
  mtd_list=[]
  with open('E:\Python\py\web'+filename,'rb+')as f:
    #获得文件句柄
    fileno=f.fileno()#返回一个整型的文件描述符,可用于底层操作系统的 I/O 操作
    while end<filesize-1:
      start=end+1
      end=start+step-1
      if end>filesize:
        end=filesize
      print ('Start:%s,end:%s'%(start,end))
      dup=os.dup(fileno)#复制文件句柄
      fd=os.fdopen(dup,'rb+',-1)
      t=Mythread(url,start,end,fd)
      t.start()
      mtd_list.append(t)
    for i in mtd_list:
      i.join()
  f.close()

以上这篇python 多线程将大文件分开下载后在合并的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pandas DataFrame创建方法的方式

pandas DataFrame创建方法的方式

在pandas里,DataFrame是最经常用的数据结构,这里总结生成和添加数据的方法: ①、把其他格式的数据整理到DataFrame中; ②在已有的DataFrame中插入N列或者N...

python字符串切割:str.split()与re.split()的对比分析

1、str.split不支持正则及多个切割符号,不感知空格的数量,比如用空格切割,会出现下面情况。 >>> s1="aa bb cc" >>> s...

python简单图片操作:打开\显示\保存图像方法介绍

python简单图片操作:打开\显示\保存图像方法介绍

一提到数字图像处理,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1、不开源,价格贵 2、软件容量大。一般3G以上,高版本甚至达5G以上。 3、只能做研究,不易转化成...

python截取两个单词之间的内容方法

1. __init__ 初始化文件路径,关键字1,关键字2; 2. key_match 使用with open 方法,以二进制方式(也可以改成utf-8,GB2312)读取文件内容(支持...

python实现画一颗树和一片森林

python实现画一颗树和一片森林

本文实例为大家分享了python画一颗树和一片森林的具体代码,供大家参考,具体内容如下 实现效果 代码在这里 from turtle import Turtle def tree...