2014-02-24 1 views
5

파이썬 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

파이썬으로 진행 막대 만들기 : http://thelivingpearl.com/2012/12/31/creating-progress-bars-with-python/ –

+1

파이썬 2의 경우 'percentComplete' 행을 변경해야합니다 '% progressComplete = round (float (self.sizeWritten)/float (self.totalSize))) * 100)' – JeffThompson

+0

[progressbar]라는 모듈이있다. (https://pypi.python.org/pypi/progressbar). 나는 그것이 ftplib과 함께 작동하는지 점검하지 않았지만 어떤 경우 든 진행 막대를 렌더링하기위한 꽤 완벽한 모듈입니다 – Fnord

답변

5

내가 생각할 수있는 방법.

  • 이 값은 글로벌 수 있고, 0으로 초기화 (기본적으로는 호출자 저장 수단)
    1. 이 값에 통과

      하고 결과를 반환 : 다음의 모든 변수의 "ownwership"를 교대 파일 상단 (global 키워드에서 읽음)
    2. 업로드 추적을 처리 할 클래스의 멤버 함수로이 함수가 있어야합니다. 그런 다음 sizeWritten을 해당 클래스의 인스턴스 변수로 만듭니다.
  • +1

    솔루션 # 3을 사용했고 작동했습니다. 작업 코드로 제 질문을 업데이트 할 것입니다. – Gab

    +1

    @Gab : option :'3 *'nonlocal sent_bytes와 함께 클로저를 만든다. (예 : [make_counter()'] (http://stackoverflow.com/q/13857/4279) – jfs

    +0

    나는 로컬이 아닌, @JFSebastian이 제안했듯이. 여기에서 print_transfer_status 메소드를 볼 수 있습니다 (https://bitbucket.org/dkurth/ftp_connection.py). –