Setting a try / timeout with ftplib in python?

夙愿已清 提交于 2019-12-23 05:10:56

问题


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.



来源:https://stackoverflow.com/questions/20436922/setting-a-try-timeout-with-ftplib-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!