2011-11-26 62 views
2

我已經到處找,找不到這個問題的修復,FTPLIB storbinary回調。 這是我第一次使用回調所以它可能是愚蠢的東西,我有一些代碼,應該叫我每次函數8192個字節上傳我認爲(這就是我的研究後認爲回調的工作)。FTPLIB回調不工作 - 的Python 3

#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

一個回調,因爲顧名思義就是當你告訴一些代碼段(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

+0

噢 - 沒想到!對不起,我忘了添加,FTP連接是在一個單獨的線程中,而回調函數在主線程中,所以傳遞變量有點棘手。最好是將函數定義在另一個線程中,這樣它可以在主線程中工作或保留函數,因此每次運行另一個線程時都不會定義它(很多)? – CallumA

+0

即使您在另一個線程中定義回調函數,回調也會在調用'storbinary'的同一個線程中運行。定義一個函數相當快,因爲​​整個函數體只能由Python編譯一次,但使它成爲一種方法似乎對我來說是最乾淨的方法。 – yak