我到处都找过了,找不到解决这个问题的方法,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 的文件也是如此。我究竟做错了什么? 提前致谢
请您参考如下方法:
回调,顾名思义,就是当您告诉一段代码 (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.ftpcallback 到 storbinary 调用。然后您可以在方法中简单地使用 self.intid。
