在python中使用ftplib设置try / timeout?

时间:2013-12-07 02:41:57

标签: python python-2.7 ftplib

如何设置超时为10秒,如果上传失败或超时再试?

当前代码:

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()

尝试以下

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()

但是它上传每个列表3次,它应该上传列表,如果它超时那么它应该再试一次但是如果它超过3次它应该从列表文件中删除内容,如else中所示。如果它成功上传它不应再试一次,它不应该传递else语句

感谢
- Hyflex

1 个答案:

答案 0 :(得分:3)

您可以在timeout构造函数中指定FTP参数(只要您运行的是2.6 +)。

  

class ftplib.FTP([host[, user[, passwd[, acct[, timeout]]]]])

     

返回FTP类的新实例。提供host后,将调用方法connect(host)。当给出user时,另外调用方法login(user, passwd, acct)(其中passwdacct默认为空字符串,如果没有给出)。可选的timeout参数指定阻塞操作(如连接尝试)的超时(以秒为单位)(如果未指定,将使用全局默认超时设置)。

我认为花费时间超过timeout的后续拦截操作会引发socket.timeout异常。您可以捕获它们并根据需要重试。

相关问题