2011-08-05 12 views
2

urllib2を使用して、おおよそthisメソッドに基づいて再開ダウンローダを作成しています。私はプログラムを終了して再起動し、途中でダウンロードを開始し、一度にダウンロードしたのと同じサイズになるファイルをダウンロードします。ネットワークが再接続したときにPython urllib2がダウンロードを再開しない

ただし、ネットワークを無効にして再度有効にしたときにテストしましたが、正しくダウンロードされません。ファイルサイズがファイルのサイズよりも長くなり、ファイルが正しく動作しません。私が見逃したことはありますか?これはurllib2のバグでしょうか?

import urllib2 
    opener = urllib2.build_opener(); 

    self.count = 0 # Counts downloaded size. 
    self.downloading = True 
    while (not(self.success) and self.downloading): 
     try: 
      self.Err = "" 
      self._netfile = self.opener.open(self.url) 
      self.filesize = float(self._netfile.info()['Content-Length']) 

      if (os.path.exists(self.localfile) and os.path.isfile(self.localfile)): 
       self.count = os.path.getsize(self.localfile) 
      print self.count,"of",self.filesize,"downloaded." 
      if self.count >= self.filesize: 
       #already downloaded 
       self.downloading = False 
       self.success = True 
       self._netfile.close() 
       return 

      if (os.path.exists(self.localfile) and os.path.isfile(self.localfile)): 
       #File already exists, start where it left off: 
       #This seems to corrupt the file sometimes? 
       self._netfile.close() 
       req = urllib2.Request(self.url) 
       print "file downloading at byte: ",self.count 
       req.add_header("Range","bytes=%s-" % (self.count)) 
       self._netfile = self.opener.open(req) 
      if (self.downloading): #Don't do it if cancelled, downloading=false. 
       next = self._netfile.read(1024) 
       self._outfile = open(self.localfile,"ab") #to append binary 
       self._outfile.write(next) 
       self.readsize = desc(self.filesize) # get size mb/kb 
       self.count += 1024 
       while (len(next)>0 and self.downloading): 
        next = self._netfile.read(1024) 
        self._outfile.write(next) 
        self.count += len(next) 
       self.success = True 
     except IOError, e: 
      print e 
      self.Err=("Download error, retrying in a few seconds: "+str(e)) 
      try: 
       self._netfile.close() 
      except Exception: 
       pass 
      time.sleep(8) #Then repeat 
+0

resurumeを行うことができる(ほとんど)ドロップインのurllibの置き換えがあります:http://urlgrabber.baseurl.org/ –

+0

ネットワークを無効/有効にしてみましたか?それは自動的に正しく再ダウンロードされますか? – NoBugs

+0

私はそれがLinuxパッケージ管理の中で内部的に使われていたと思うので、かなりうまくテストする必要があります。それはリトライ回数などの設定もしています。 –

答えて

1

私はそれを修正しているようだ例外IOErrorハンドラ内self._netfile.close()、とself._outfile.close()を追加。私はこのエラーは、それを閉じずに再び追加するために開くことによって引き起こされたと思います。

関連する問題