[Tutor] saving output data in a file

Dave Angel davea at ieee.org
Sun Dec 6 12:56:18 CET 2009


spir wrote:
> <snip>
>
>
> class Out(file):
> 	def __init__(self, filename, toconsole=True, numberlines=True):
> 		file.__init__(self, filename, 'r')
> 		print self
> 		# debug output to console
> 		self.toconsole = toconsole
> 		# line numbering
> 		self.numberlines = numberlines
> 		if self.numberlines:
> 			self.linenumber = 0
> 		# save default stdout
> 		self.console = sys.stdout
> 	def write(self, msg):
> 		if self.numberlines:
> 			self.linenumber += 1
> 			linenumber = "%3d	" % self.linenumber
> 		else:
> 			linenumber = ""
> 		text = "%s%s\n" %(linenumber, msg)
> 		self.write(text)
> 		if self.toconsole:
> 			self.console.write(text)
> 	def close(self):
> 		# restore default stdout
> 		sys.stdout = self.console
> 		# close file
> 		self.close()
>
>
>
>   
In your call to __init__(), shouldn't the file mode have been "w"  not "r" ?

Aren't those write() and close() methods infinitely recursive?  I 
suspect you meant something like:
        file.write(self, text)       and
        file.close(self)

Also, I'm not really sure what you're doing with self.console versus 
sys.stdout.  Since you "restore" it in close(), I'm assuming you meant 
to change it at some point in your code.  And if you are going to change 
it, you should flush it first.  If you hadn't had the "restore" code, 
I'd have guessed instead that you were trying to force all the output to 
go to the original stdout, even if the caller has reassigned it in the 
meantime.


I didn't actually try your class, but these are problems that jumped out 
at me.

DaveA



More information about the Tutor mailing list