ftplib 回调不工作 - Python 3
我到处找都没找到解决这个问题的方法,关于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的文件。我到底哪里出错了呢? 提前谢谢你们的帮助!
1 个回答
1
回调函数,顾名思义,就是你告诉某段代码(比如ftplib)在需要的时候再“回叫”你。你之前做的事情是自己调用了ftpcallback
这个函数,并把它的返回值(因为它没有返回任何东西,所以是None
)传给了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
了。