我使用Python 3.4上傳了一個FTP文件。Python ftplib:顯示FTP上傳進度
我希望能夠在上傳文件時顯示進度百分比。這是我的代碼:
from ftplib import FTP
import os.path
# Init
sizeWritten = 0
totalSize = os.path.getsize('test.zip')
print('Total file size : ' + str(round(totalSize/1024/1024 ,1)) + ' Mb')
# Define a handle to print the percentage uploaded
def handle(block):
sizeWritten += 1024 # this line fail because sizeWritten is not initialized.
percentComplete = sizeWritten/totalSize
print(str(percentComplete) + " percent complete")
# Open FTP connection
ftp = FTP('website.com')
ftp.login('user','password')
# Open the file and upload it
file = open('test.zip', 'rb')
ftp.storbinary('STOR test.zip', file, 1024, handle)
# Close the connection and the file
ftp.quit()
file.close()
如何在句柄函數中讀取塊的數量?
更新
閱讀CMD的回答後,我已將此添加到我的代碼:
class FtpUploadTracker:
sizeWritten = 0
totalSize = 0
lastShownPercent = 0
def __init__(self, totalSize):
self.totalSize = totalSize
def handle(self, block):
self.sizeWritten += 1024
percentComplete = round((self.sizeWritten/self.totalSize) * 100)
if (self.lastShownPercent != percentComplete):
self.lastShownPercent = percentComplete
print(str(percentComplete) + " percent complete")
而且我所說的FTP上傳這樣的:
uploadTracker = FtpUploadTracker(int(totalSize))
ftp.storbinary('STOR test.zip', file, 1024, uploadTracker.handle)
創建進度條與Python:http://thelivingpearl.com/2012/12/31/creating-progress-bars-with-python/ –
對於Python 2,你需要改變'percentComplete'線((float(self.sizeWritten)/ float(self.totalSize))* 100)' – JeffThompson
有一個叫做[progressbar]的模塊(https://pypi.python.org/pypi/progressbar )。我還沒有檢查它是否可以和ftplib一起工作,但無論如何這是一個非常完整的模塊來渲染進度條 – Fnord