2

I'm trying to upload lots of files using python's ftplib.
What kind of exception should I catch to be sure the problem is a connection error (so I can re-connect)?


Edit:
I tried all_errors in this scenario:

  • Connected to FTP server by ftplib and paused application (via debugger) before file upload
  • Closed connection via server
  • Resumed Application

With this code:

        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

exception caught but all_errors was empty:

e   EOFError:   
    args    tuple: ()   
    message str:    
Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • I don't understand what do you wanna tell us. So `ftplib.all_errors` worked but it was empty? – dav1d Jan 13 '13 at 13:05
  • @dav1d: yes;(check my second edit); not always but most of times it has a empty tuple! (while it is caught!!) – Ariyan Jan 13 '13 at 13:25
  • 1
    `e` is the instance of the error which is caught, it simply means no arguments were passed on initilization to the EOFError. That is nothing you have to care about. – dav1d Jan 13 '13 at 16:21

3 Answers3

2

You can look it up in the documentation: http://docs.python.org/2/library/ftplib.html#ftplib.error_reply

Also don't forget: http://docs.python.org/2/library/ftplib.html#ftplib.all_errors

dav1d
  • 5,917
  • 1
  • 33
  • 52
2

Try like this,

import socket
import ftplib

try:
    s = ftplib.FTP(server , user , password) 
except ftplib.all_errors as e:
    print "%s" % e
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42
2

A simple way to catch exceptions both to and from a ftp server may be:

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
gmas80
  • 1,218
  • 1
  • 14
  • 44