Не найдя в сети ни одного примера загрузчика файлов с отображением текущего статуса загрузки и возможностью докачки решил написать свой. Быть может кому пригодится.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | # -*- coding: utf-8 -*-
import os,sys,urllib2
def getNewPath(url, name=None, directory=None):
if directory==None: directory=os.curdir
if not os.path.exists(directory): os.mkdir(directory)
if name==None:
path="%s%s%s" % (
directory,
os.sep,
url.split("/")[-1])
else:
path="%s%s%s" % (
directory,
os.sep,
name)
return path
def downloadfile(url, newName=None, dir=None):
newPath = getNewPath(url, newName, dir)
if not os.path.exists(newPath):
localLen = 0
else:
localLen = os.path.getsize(newPath)
req = urllib2.Request(url)
req.headers['Range'] = 'bytes='+str(localLen)+'-'
print "Sending request..."
remoteLen = 0
try:
res = urllib2.urlopen(url)
remoteLen = int(res.info().getheader("Content-Length"))
except urllib2.HTTPError, e:
print e
return
except urllib2.URLError, e:
print e
return
print "Received code:", res.getcode()
print "Length: %d (%.02fM) [%s]" % (
remoteLen,
remoteLen/1024.0/1024.0,
res.info().getheader("Content-Type"))
print "Saving to: ", newPath
if localLen == 0:
localFile = open(newPath, "wb")
elif localLen < remoteLen:
localFile = open(newPath, "ab")
elif localLen == remoteLen:
print "File has downloaded already."
return
try:
remoteFile = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e
return
except urllib2.URLError, e:
print e
return
print "Downloading %s - %s (%s bytes) ..." % (remoteFile.url, newPath, remoteLen)
if remoteLen != 0:
remoteLen = float(remoteLen)
bytesRead = float(localLen)
for line in remoteFile:
bytesRead += len(line)
sys.stdout.write("\r%s: %.02f/%.02f kb (%d%%)" % (
newPath,
bytesRead/1024.0,
remoteLen/1024.0,
100*bytesRead/remoteLen))
sys.stdout.flush()
localFile.write(line)
remoteFile.close()
localFile.close()
print "\nFile %s has been downloaded.\n" % newPath
|
P.S. Работает на честном слове :-)
Репозиторий проекта на
github.com
Комментарии