捕获由ftplib中的连接错误引起的异常

时间:2013-01-13 12:40:13

标签: python exception ftplib

我正在尝试使用python的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:    

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

试试这个,

import socket
import ftplib

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

答案 2 :(得分: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