7

我正在编写一个使用 FTPLib 来获取文件的模块。我想找到一种将值(除了块之外)传递给回调的方法。本质上,我的回调是

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

我需要打电话

ftp.retrbinary('RETR somefile', handleDownload)

并让它传递一个文件句柄。有没有办法做到这一点?

4

2 回答 2

6

您可以使用lambda关闭fileToWrite变量:

fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))
于 2012-08-21T17:54:59.870 回答
0

这段代码对我有用。

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)



    
于 2021-07-17T12:48:27.553 回答