0
def download(self):
    ftp = self.connect()
    try:
        size = ftp.size(filename=self.filename)
        print "Total size of {filename} is {size}".format(filename=self.filename, size=size)
        written_till_now = 0
        def handle(bytes):
            f.write(bytes)
            print "written bytes: {}".format(bytes)

        with open(self.filename, 'wb') as f:
            ftp.retrbinary('RETR {}'.format(self.filename), handle)
    except (socket.error, error_perm) as e:
        raise DownloaderException("Error in downloading file {filename}: {message}".format(filename=self.filename, message=str(e)))
    except EOFError as e:
        print "file {filename} downloaded successfully".format(filename=self.filename)

I want to keep track of the amount of data i've currently downloaded and later do some additional stuff also for every stream of data i download.

I created a handle function inside the download function.

Python ftblip.retrbinary provides the data to the given callback. In my case handle but somehow it is not executing.

Also I doubt i am not understanding the scope of variables when it comes to nested functions. In my understanding I can use variable defined in parent scope in the child scope as long as i am not modifying them.But in this case f is a object and i am not modifying it rather calling its method write. Please correct me if i am missing something.

Raheel
  • 7,354
  • 5
  • 40
  • 79

1 Answers1

1

The handle function doesn't have access to the scoped f variable. Instead you can pass the open file directly to handle.

def handle(fp, bytes):
    fp.write(bytes)
    print "written bytes: {}".format(bytes)

with open(self.filename, 'wb') as f:
    ftp.retrbinary('RETR {}'.format(self.filename), lambda b: handle(f, b))
Håken Lid
  • 18,252
  • 8
  • 40
  • 58