2

我到处找,找不到解决这个问题的方法,ftplib storbinary 回调。这是我第一次使用回调,所以它可能很愚蠢,我假设每次上传 8192 字节时我都有一些代码应该调用我的函数(这就是我认为回调在研究后的工作方式)。

#In main thread
def ftpcallback(intid):
    ftpuploaded = transStatus[intid][3] + 8192 #transStatus[intid] equals 0 to start with
    if ftpuploaded > transStatus[intid][2]: ftpuploaded = transStatus[intid][2] #Is this needed? It's supposed to just keep the value below the file size
    transStatus[intid][3] = ftpuploaded
    print (transStatus[intid][3]) #Always outputs 8192
    print("Callback called")

#Not in main thread
#FTP and file open code

self.ftp.storbinary("STOR " + self.destname, self.f, 1, ftpcallback(self.intid)) #1 to (hopefully) spam the output more

#close FTP and file code

无论何时运行,回调只运行一次,即使是 10MB 的文件。我究竟做错了什么?提前致谢

4

1 回答 1

1

顾名思义,回调就是当您告诉一段代码(ftplib)给您回电时。您所做的是自己调用该ftpcallback函数并将其返回值(这是None因为它什么都不做return)传递给该storbinary方法。

相反,您只想在调用时传递函数对象storbinary,让 ftplib 为您调用此函数。你不想自己称呼它。因此,您需要摆脱(...).

intid = self.intid
def ftpcallback():
    ftpuploaded = transStatus[intid][3] + 8192  # transStatus[intid] equals 0 to start with
    if ftpuploaded > transStatus[intid][2]:
        ftpuploaded = transStatus[intid][2]  # Is this needed? It's supposed to just keep the value below the file size
    transStatus[intid][3] = ftpuploaded
    print(transStatus[intid][3])  # Always outputs 8192
    print("Callback called")

#FTP and file open code

self.ftp.storbinary("STOR " + self.destname, self.f, 1, ftpcallback)

ftplib 文档没有说明回调参数,所以我假设它在调用回调时没有将任何参数传递给回调。因此,您ftpcallback必须是可调用的ftpcallback(),即没有参数。这就是我删除intid参数并intid = self.intid在函数之前添加的原因。

另一种方法是定义ftpcallback类的方法 ( def ftpcallback(self):) 并传递self.ftpcallbackstorbinary调用。然后你可以简单地self.intid在方法内部使用。

于 2011-11-26T19:16:56.817 回答