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

5 投票
1 回答
2234 浏览
提问于 2025-04-16 21:52

我正在往一个FTP服务器上传很多文件。在上传过程中,服务器超时了,这让我无法继续上传。有没有人知道怎么判断服务器是否超时,重新连接后继续传输数据?我使用的是Python的ftp库来进行传输。

谢谢!

1 个回答

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

如果这样还不够好,那你可能需要选择一个不同的API。Twisted框架有一个FTP协议支持,应该可以让你添加超时逻辑。

撰写回答