捕获进出 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