7

I'm writing a module that uses FTPLib to fetch files. I want to find a way to pass a value(in addition to the block) to the callback. Essentially, my callback is

 def handleDownload(block, fileToWrite):
    fileToWrite.write(block)

And I need to call

ftp.retrbinary('RETR somefile', handleDownload)

And have it pass a file handle. Is there a way to do this?

Feasoron
  • 3,471
  • 3
  • 23
  • 34

2 Answers2

6

You can close over the fileToWrite variable with a lambda:

fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 1
    Is there any other way to download the file other than saying 'write'? I want to be able to retain the timestamp given on the FTP site. – Shyam Sunder Mar 14 '13 at 11:48
0

This code worked for me.

class File:

    cleared = False

    def __init__(self, filepath):
        self.filepath = filepath

    def write(self,block): 
        if not File.cleared:
            with open(f'{self.filepath}', 'wb') as f:
                File.cleared = True
                with open(f'{self.filepath}', 'ab') as f:
                f.write(block)
        else:
             with open(f'{self.filepath}', 'ab') as f:
                 f.write(block)

ftp.retrbinary("RETR somefile", File(filepath).write)



    
Eugene
  • 1
  • 1