一個簡單的方法來捕捉異常既從一個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
我不明白你怎麼想告訴我們的。所以'ftplib.all_errors'工作,但它是空的? – dav1d
@ dav1d:是的;(檢查我的第二個編輯);並不總是,但大多數時候它有一個空元組! (當它被捕獲!!) – RYN
'e'是被捕獲的錯誤的實例,它僅僅意味着沒有參數被傳遞給EOFError。這不是你必須關心的。 – dav1d