2014-02-24 130 views
5

我使用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) 
+1

创建进度条与Python:http://thelivingpearl.com/2012/12/31/creating-progress-bars-with-python/ –

+1

对于Python 2,你需要改变'percentComplete'线((float(self.sizeWritten)/ float(self.totalSize))* 100)' – JeffThompson

+0

有一个叫做[progressbar]的模块(https://pypi.python.org/pypi/progressbar )。我还没有检查它是否可以和ftplib一起工作,但无论如何这是一个非常完整的模块来渲染进度条 – Fnord

回答

5

有三个非哈克我能想到的方式。所有的再移位的可变的“ownwership”:

  1. 具有值传入并返回结果(基本上意味着其存储在呼叫方)
  2. 具有值是全局的,并将其初始化为0和文件的顶部。 (请阅读global关键字)
  3. 具有此功能作为类的成员函数来处理上载跟踪。然后使sizeWritten成为该类的实例变量。
+1

我使用了解决方案#3,它工作,我将用工作代码更新我的问题。 – Gab

+1

@Gab:option:'3 *'用'nonlocal sent_bytes'做一个闭包例如['make_counter()'](http://stackoverflow.com/q/13857/4279) – jfs

+0

我已经使用nonlocal,正如@JFSebastian所建议的那样。你可以在这里看到它(查找print_transfer_status方法):https://bitbucket.org/dkurth/ftp_connection.py –