2

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

3 回答 3

2

您可以在文档中查找它:http: //docs.python.org/2/library/ftplib.html#ftplib.error_reply

也不要忘记:http ://docs.python.org/2/library/ftplib.html#ftplib.all_errors

于 2013-01-13T12:42:09.600 回答
2

像这样试试

import socket
import ftplib

try:
    s = ftplib.FTP(server , user , password) 
except ftplib.all_errors as e:
    print "%s" % e
于 2013-01-13T12:46:14.903 回答
2

捕获进出 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
于 2014-10-30T02:37:52.763 回答