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

use*_*864 5 python

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

谢谢

wbe*_*rry 4

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

由于 storbinary 和 retrbinary 方法允许您提供回调,因此您可以实现看门狗计时器。每次获取数据时都会重置计时器。如果您没有至少每 30 秒(或其他)获取数据,看门狗将尝试中止并关闭 FTP 会话,并将事件发送回您的事件循环(或其他)。

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()
Run Code Online (Sandbox Code Playgroud)

如果这还不够好,那么您似乎必须选择不同的 API。Twisted 框架具有FTP 协议支持,允许您添加超时逻辑。