我正在编写一个使用 FTPLib 来获取文件的模块。我想找到一种将值(除了块之外)传递给回调的方法。本质上,我的回调是
def handleDownload(block, fileToWrite):
fileToWrite.write(block)
我需要打电话
ftp.retrbinary('RETR somefile', handleDownload)
并让它传递一个文件句柄。有没有办法做到这一点?
您可以使用lambda关闭fileToWrite
变量:
fileToWrite = open("somefile", "wb")
ftp.retrbinary("RETR somefile", lambda block: handleDownload(block, fileToWrite))
这段代码对我有用。
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)