繁体   English   中英

如何在 Python 中检测 ftp 服务器超时

[英]How to detect ftp server timeouts in Python

将大量文件上传到 FTP 服务器。 在我上传的过程中,服务器超时,阻止我进一步上传。 有谁知道检测服务器是否超时、重新连接并继续传输数据的方法? 我正在使用 Python ftp 库进行传输。

谢谢

您可以简单地为连接指定超时,但对于文件传输或其他操作期间的超时,它并不是那么简单。

因为 storbinary 和 retrbinary 方法允许您提供回调,所以您可以实现看门狗定时器。 每次获得数据时,您都会重置计时器。 如果您至少每 30 秒(或其他任何时间)未获取数据,则看门狗将尝试中止并关闭 FTP session 并将事件发送回您的事件循环(或其他)。

ftpc = FTP(myhost, 'ftp', 30)

def timeout():
  ftpc.abort()  # may not work according to docs
  ftpc.close()
  eventq.put('Abort event')  # or whatever

timerthread = [threading.Timer(30, timeout)]

def callback(data, *args, **kwargs):
  eventq.put(('Got data', data))  # or whatever
  if timerthread[0] is not None:
    timerthread[0].cancel()
  timerthread[0] = threading.Timer(30, timeout)
  timerthread[0].start()

timerthread[0].start()
ftpc.retrbinary('RETR %s' % (somefile,), callback)
timerthread[0].cancel()

如果这还不够好,看来您将不得不选择不同的 API。 Twisted 框架具有FTP 协议支持,应该允许您添加超时逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM