我使用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