我正在尝试使用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:
答案 0 :(得分:2)
您可以在文档中查找:http://docs.python.org/2/library/ftplib.html#ftplib.error_reply
另请不要忘记:http://docs.python.org/2/library/ftplib.html#ftplib.all_errors
答案 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