ftplib回调不工作python3

2024-06-16 09:35:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我到处找遍了,但找不到这个问题的解决方案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的文件也是如此。我做错什么了? 提前谢谢


Tags: andthetoselfmainftpcodethread
1条回答
网友
1楼 · 发布于 2024-06-16 09:35:24

回调,顾名思义就是当你告诉某段代码(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。在

相关问题 更多 >