add bandwidth to a file download in python
Another short code snippet I came up when writing the module download script
The following class keeps a download under a certain ratio and prints live download stats (KB/s).
PYTHON:
-
class BandwidthFile:
-
"""
-
limits the file download to a certain amount of bytes per second and prints download stats
-
"""
-
def __init__(self, filename, filesize, bytes_per_second = 20000, mode = "wb"):
-
self.fp = open(filename, "wb")
-
self.bytecounter = 0
-
self.started = datetime.datetime.now()
-
self.bytes_per_second = bytes_per_second
-
self.filesize = filesize
-
self.filename = filename
-
-
def __del__(self):
-
self.fp.close()
-
-
def write(self, bytestring):
-
self.bytecounter += len(bytestring)
-
seconds_since_started = (datetime.datetime.now() - self.started).seconds + 1
-
while (self.bytecounter / seconds_since_started)> self.bytes_per_second:
-
seconds_since_started = (datetime.datetime.now() - self.started).seconds + 1
-
time.sleep(0.1)
-
self.fp.write(bytestring)
-
sys.stdout.write("\rdownloading %s (%i/%i KB, %i KB/s)" % (self.filename, (self.bytecounter / 1024), (int(self.filesize) / 1024), (self.bytecounter /seconds_since_started / 1024)))
-
sys.stdout.flush()
To use the class with ftp:
PYTHON:
-
from ftplib import FTP
-
ftp = FTP("ftp.modland.com")
-
filesize = ftp.size(remote_filename)
-
f = BandwidthFile(local_filename, ftp_filesize)
-
ftp.retrbinary('RETR '+remote_filename, f.write)
The status line looks like this:
downloading /home/phred/modules/Skaven/beyond the network.it (95/4411 KB, 19 KB/s)
If you have suggestions how to enhance the code snippet feel free to leave a comment!