【问题标题】:Setting a try / timeout with ftplib in python?在 python 中使用 ftplib 设置尝试/超时?
【发布时间】:2013-12-07 02:41:57
【问题描述】:

如何设置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 语句

谢谢
- 海福克斯

【问题讨论】:

    标签: python python-2.7 ftplib


    【解决方案1】:

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

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

    返回FTP 类的新实例。当给定host 时,将进行方法调用connect(host)。当给定user 时,还会调用login(user, passwd, acct) 方法(其中passwdacct 在未给定时默认为空字符串)。可选的timeout 参数指定连接尝试等阻塞操作的超时时间(如果未指定,将使用全局默认超时设置)。

    我相信后续阻塞操作花费的时间比您的 timeout 更长的时间会引发 socket.timeout 异常。您可以捕获这些并根据需要重试。

    【讨论】:

      猜你喜欢
      • 2015-06-05
      • 2011-03-27
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多