国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python 多線程將大文件分開下載后在合并的實(shí)例

2020-02-15 23:35:30
字體:
供稿:網(wǎng)友

廢話不多說了,上代碼吧:

import threadingimport requestsimport timeimport osclass 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)#允許線程個數(shù)  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()#返回一個整型的文件描述符,可用于底層操作系統(tǒng)的 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)#復(fù)制文件句柄      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 多線程將大文件分開下載后在合并的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 中山市| 休宁县| 赤壁市| 屏东市| 崇信县| 屏东县| 九龙坡区| 怀化市| 龙岩市| 鹿泉市| 靖边县| 临猗县| 元氏县| 休宁县| 滦南县| 汉中市| 永昌县| 张家界市| 德昌县| 彭山县| 安阳市| 阳曲县| 阿图什市| 增城市| 贵南县| 崇明县| 松潘县| 武乡县| 兰西县| 高要市| 双城市| 南丰县| 航空| 德钦县| 济阳县| 平昌县| 三原县| 华宁县| 湖口县| 横山县| 绥棱县|