Setting a try / timeout with ftplib in python?

2019-06-13 21:00发布

问题:

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. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout 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.