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

yipeiwu_com5年前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设计】。

相关文章

星球大战与Python之间的那些事

星球大战与Python之间的那些事

Python与星球大战背后的工业光魔 提起Python语言,很多人会想起系统运维、Web开发等工作。很少有人会知道Python也能够用于电影视觉特效的制作,其中就包括了《星球大战》某些电...

详解使用python的logging模块在stdout输出的两种方法

详解使用python的logging模块在stdout输出 前言:   使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志...

Python回调函数用法实例详解

本文实例讲述了Python回调函数用法。分享给大家供大家参考。具体分析如下: 一、百度百科上对回调函数的解释: 回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数...

Python3.5面向对象程序设计之类的继承和多态详解

Python3.5面向对象程序设计之类的继承和多态详解

本文实例讲述了Python3.5面向对象程序设计之类的继承和多态。分享给大家供大家参考,具体如下: 1、继承的定义 继承是指:可以使用现有类的所有功能,并在无需重新编写原来的类的情况下...

对pycharm 修改程序运行所需内存详解

编辑PyCharm安装目录下PyCharm 4.5.3\bin下的pycharm.exe.vmoptions文件, 如下 -server -Xms128m -Xmx512m -XX:...