2014-01-24 72 views
1

我目前使用此代碼打印出使用ftp.retrbinary從ftp服務器下載的百分比,但下載完成時爲0.27%完成,並且只能說明sizeWritten以27828224位結束。我哪裏錯了?如何跟蹤使用ftp.retrbinary下載的百分比?

from ftplib import FTP 

ftp = FTP('host') 
ftp.login('usr','pass') 
totalSize = ftp.size('100file.zip') 
print(totalSize, "bytes") 

def download_file(block): 
    global sizeWritten 
    file.write(block) 
    sizeWritten += 1024 
    print(sizeWritten, "= size written", totalSize, "= total size") 
    percentComplete = sizeWritten/totalSize 
    print (percentComplete, "percent complete") 

try: 
    file = open('100file.zip', "wb") 
    ftp.retrbinary("RETR " + '100file.zip' ,download_file) 
    print("Download Successful!") 
except: 
    print("Error") 

file.close() 
ftp.close() 
+0

你怎麼知道每個塊的長度是1024字節? – Hyperboreus

+0

作爲一個方面說明,你似乎混合了比特和字節,當你的數字是4倍數或者是1/2倍時,這幾乎不可能提供幫助。 – abarnert

回答

2

你已經忽略了塊的大小,並假裝每一個都是1K:

sizeWritten += 1024 

只是修改成:

sizeWritten += len(block) 

您的客戶端可以發送一個最大模塊大小到服務器,與blocksize參數。但是你沒有通過一個,所以你得到了默認的8192.

所以,如果你只有8個因子,你爲什麼沒有得到12.5%?那麼,首先,最後一個塊總是會低於最大值,所以你應該預計會有超過12.5%。其次,你只給服務器一個塊大小;它可以自由決定它從來不想發送超過4K的數據,在這種情況下,你會得到超過25%的代價。