问题
How can I set a timeout of 10~ seconds and if it fails to upload or times out to try again?
Current code:
print "Uploading LIST{}.html".format(counter)
ftp_session = ftplib.FTP('ftp.website.com','admin@website.com','password123')
rss_ftp_file = open('OUTPUT/LISTS/LIST{}.html'.format(counter),'r')
ftp_session.cwd("/LISTS/")
ftp_session.storlines('STOR LIST{}.html.tmp'.format(counter), rss_ftp_file)
rss_ftp_file.close()
ftp_session.rename('LIST{}.html.tmp'.format(counter), 'LIST{}.html'.format(counter))
ftp_session.quit()
Tried the following
for i in range(3):
try:
print "Uploading LIST{}.html".format(counter)
ftp_session = ftplib.FTP('ftp.website.com','admin@website.com','password123','',60)
rss_ftp_file = open('OUTPUT/LISTS/LIST{}.html'.format(counter),'r')
ftp_session.cwd("/LISTS/")
ftp_session.storlines('STOR LIST{}.html.tmp'.format(counter), rss_ftp_file)
rss_ftp_file.close()
ftp_session.rename('LIST{}.html.tmp'.format(counter), 'LIST{}.html'.format(counter))
ftp_session.quit()
break
except:
continue
else:
open('OUTPUT/LISTS/LIST{}.html'.format(counter),'w').close()
But it uploads each list 3 times, it should upload the list and if it timesout then it should try again but if it timesout 3 times it should delete the content from the listfile as shown in the else. If it successfully uploads it shouldn't try again and it shouldn't pass the else statement
Thanks
- Hyflex
回答1:
You can specify a timeout
parameter in the FTP
constructor (as long as you're running 2.6+).
class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])
Return a new instance of the
FTP
class. Whenhost
is given, the method callconnect(host)
is made. Whenuser
is given, additionally the method calllogin(user, passwd, acct)
is made (wherepasswd
andacct
default to the empty string when not given). The optionaltimeout
parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used).
I believe subsequent blocking operations that take longer than your timeout
will raise socket.timeout
exception. You can catch those and retry as needed.
来源:https://stackoverflow.com/questions/20436922/setting-a-try-timeout-with-ftplib-in-python