2012-07-24 68 views
3

我有一個使用ftplib的ftp程序,在過去的幾天裏,我一直在想如何爲retrbinary和storbinary實現一個進度條。我正在嘗試使用progressbar 2.3模塊,但一直沒有讓它配合使用。我認爲這可能源於對回調函數工作原理的誤解。無論如何,這是我的。Python:ftp和progressbar 2.3

import progressbar 
import ftplib 


ftp = ftplib.FTP() 
ftp.connect("host", "port") 
ftp.login("user", "pwd") 


widgets = ['Downloading: ', Percentage(), ' ', Bar(marker=RotatingMarker()), 
     ' ', ETA(), ' ', FileTransferSpeed()] 
pbar = ProgressBar(widgets=widgets, maxval=1024).start() 

def callback(p): 
    for i in range(1024): 
     pbar.update(10*i+1) 
     pbar.finish() 

ftp.storbinary("STOR iTunesSetup.exe", open("iTunesSetup.exe"), callback, blocksize=1024) 

我得到這個錯誤,雖然這僅僅是我曾經嘗試這樣做的途徑之一:

Traceback (most recent call last): 
    File "progrbar.py", line 7, in <module> 
    ftp.connect("host", "port") 
    File "/usr/lib/python2.7/ftplib.py", line 132, in connect 
    self.sock = socket.create_connection((self.host, self.port), self.timeout) 
    File "/usr/lib/python2.7/socket.py", line 553, in create_connection 
    for res in getaddrinfo(host, port, 0, SOCK_STREAM): 
socket.gaierror: [Errno -8] Servname not supported for ai_socktype 

我可以不說這句話回調FTP服務器工作得很好,有更多然後足夠的空間下載。如果有人能給我一些指點,我將不勝感激。

回答

6

對於任何未來的訪客,這是我做到了......

def handleupload(self, block): 
    self.pbar.update(self.pbar.currval+len(block)) 

def upload(self): 
    try: 
     if os.path.getsize(self.filename) == 0: 
      print "%s 0 bytes passing..." % self.filename 
     else: 
      print "Uploading %s-%d-bytes" % (self.filename, self.ftp.size(self.filename)) 
      self.pbar=ProgressBar(widgets=[FileTransferSpeed(),' ', Bar(marker=RotatingMarker()), ' ', 
                Percentage(),' ', ETA()], maxval=os.path.getsize(self.filename)).start() 
      self.ftp.storbinary("STOR " + self.filename, open(self.filename), 
                 callback = s.handleupload, blocksize = 1024) 
      self.pbar.finish() 
      print "Finished" 
    except (error_perm, error_temp, Exception), self.exc: 
     print self.exc