2013-01-13 53 views
1

我试图使用python的ftplib上传大量文件。
我应该捕捉什么样的异常以确定问题是连接错误(所以我可以重新连接)?捕获ftplib中的连接错误导致的异常


编辑:
我在这种情况下试图all_errors

  • 通过ftplib连接到FTP服务器和文件上传之前暂停的应用程序(通过调试器)
  • 通过服务器关闭连接
  • 恢复申请

有了这个代码:

 try:   
      self.f.cwd(dest) 
      return self.f.storbinary(('STOR '+n).encode('utf-8'), open(f,'rb')) 
     except ftplib.all_errors as e: 
      print e 

异常捕获,但all_errors是空的:

e EOFError: 
    args tuple:() 
    message str:  
+0

我不明白你怎么想告诉我们的。所以'ftplib.all_errors'工作,但它是空的? – dav1d

+0

@ dav1d:是的;(检查我的第二个编辑);并不总是,但大多数时候它有一个空元组! (当它被捕获!!) – RYN

+1

'e'是被捕获的错误的实例,它仅仅意味着没有参数被传递给EOFError。这不是你必须关心的。 – dav1d

回答

1

试试这个,

import socket 
import ftplib 

try: 
    s = ftplib.FTP(server , user , password) 
except ftplib.all_errors as e: 
    print "%s" % e 
+0

请检查我的编辑 – RYN

1

一个简单的方法来捕捉异常既从一个FTP服务器可能是:

import ftplib, os 

def from_ftp(server, path, data, filename = None): 
    '''Store the ftp data content to filename (anonymous only)''' 
    if not filename: 
     filename = os.path.basename(os.path.realpath(data)) 

    try: 
     ftp = ftplib.FTP(server) 
     print(server + ' -> '+ ftp.login())   
     print(server + ' -> '+ ftp.cwd(path)) 
     with open(filename, 'wb') as out: 
      print(server + ' -> '+ ftp.retrbinary('RETR ' + data, out.write)) 

    except ftplib.all_errors as e: 
     print('Ftp fail -> ', e) 
     return False 

    return True 

def to_ftp(server, path, file_input, file_output = None): 
    '''Store a file to ftp (anonymous only)''' 
    if not file_output: 
     file_output = os.path.basename(os.path.realpath(file_input)) 

    try: 
     ftp = ftplib.FTP(server) 
     print(server + ' -> '+ ftp.login())   
     print(server + ' -> '+ ftp.cwd(path)) 
     with open(file_input, 'rb') as out: 
      print(server + ' -> '+ ftp.storbinary('STOR ' + file_output, out)) 

    except ftplib.all_errors as e: 
     print('Ftp fail -> ', e) 
     return False 

    return True 
相关问题