2014-02-24 163 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 –