Pass a value to the ftp.retrbinary callback
Asked Answered
D

2

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?

Dusky answered 21/8, 2012 at 17:30 Comment(0)
W
6

You can close over the fileToWrite variable with a lambda:

fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))
Wanwand answered 21/8, 2012 at 17:54 Comment(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.Lilalilac
S
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)



    
Setup answered 17/7, 2021 at 12:48 Comment(3)
the code should work, however You could have just made it into one function not make a whole classCentrepiece
one function will allow you to add only last binary block.Setup
to be fair I don't even remember commenting here, so I forgot what was my thought, so ... carry on, have a nice dayCentrepiece

© 2022 - 2024 — McMap. All rights reserved.