2011-07-19 117 views
5

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

感谢

+1

你会得到什么样的回应(如果有的话)?它是[400个代码之一](http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes)? –

回答

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。扭曲的框架有FTP protocol support,应该允许你添加超时逻辑。