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

前端之家收集整理的这篇文章主要介绍了如何在Python中检测ftp服务器超时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

谢谢

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

因为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 protocol support,允许您添加超时逻辑.

原文链接:https://www.f2er.com/python/439169.html

猜你在找的Python相关文章