Python:ReliableFTP

From Devicenull's Code

Jump to: navigation, search

This is a simple wrapper around the default FTP class, that retries operations once if they fail. Useful for dealing with bad connections or FTP servers

from ftplib import FTP
 
class ReliableFTP:
	def __init__(self,host,user,password):
		self.host = host
		self.user = user
		self.password = password
		self.cur_path = ""
		self.reconnect()
 
	def reconnect(self):
		self.ftp = FTP(self.host,self.user,self.password)
		self.ftp.cwd(self.cur_path)
 
	def pwd(self):
		try:
			ret = self.ftp.pwd()
			return ret
		except:
			self.reconnect()
			ret = self.ftp.pwd()
			return ret
 
	def cwd(self,dest):
		try:
			self.ftp.cwd(dest)
			self.cur_path = self.ftp.pwd()
		except:
			self.reconnect()
			self.ftp.cwd(dest)
			self.cur_path = self.ftp.pwd()
 
	def retrlines(self,cmd,lines):
		try:
			ret = self.ftp.retrlines(cmd,lines)
			return ret
		except:
			self.reconnect()
			ret = self.ftp.retrlines(cmd,lines)
			return ret
 
	def retrbinary(self,cmd,bin):
		try:
			ret = self.ftp.retrbinary(cmd,bin)
			return ret
		except:
			self.reconnect()
			ret = self.ftp.retrbinary(cmd,bin)
			return ret					
 
	def mkd(self,directory):
		try:
			self.ftp.mkd(directory)
		except:
			self.reconnect()
			self.ftp.mkd(directory)
 
	def storbinary(self,cmd,f):
		try:
			self.ftp.storbinary(cmd,f)
		except:
			self.reconnect()
			self.ftp.storbinary(cmd,f)
Personal tools