[Tutor] saving output data in a file

spir denis.spir at free.fr
Sat Dec 5 12:19:05 CET 2009


Dave Kuhlman <dkuhlman at rexx.com> dixit:

> On Fri, Dec 04, 2009 at 01:13:42PM +0530, Prasad Mehendale wrote:
> > I am a beginner. I want to save the output data of the following programme in 
> > a file through the programme. Please suggest me the way. I am using Python 
> > 2.3.3 on mandrake linux 10 and using "Idle" to save the output to a file 
> > presently. 
> > Thanks in advance.
> > 
> > #programme to calculate various parameters for a dc-generator.
> > import math
> > #import os
> > #flux is assumed to be .005Wb, and A=parallel paths = 2 for wave winding
> > polerpm=[]
> > for ConductorsPerSlot in range(1,11):
> >     """ we consider that output voltage is 20 V DC """
> >     PoleRpmProduct=20000/ConductorsPerSlot
> >     polerpm.append(PoleRpmProduct)
> > print '(Pole*RPM) product for various values of conductors/slot is: \n', 
> > polerpm
> > for poles in range(2,18,2):
> >     print
> >     print '\n For number of poles='+str(poles) +'  RPM values are: '
> >     for i in range(len(polerpm)):
> >                    rpm=polerpm[i]/poles
> >                    print rpm,
> > 
> > 
> 
> Another suggestion is to define a class that contains a method
> named "write" which takes one argument which is the text to be
> printed.
> 
> This approach is useful when there are print statements in code
> that is not under your control, for example imported modules.
> 
> There is a note about this here:
> 
>     http://docs.python.org/library/sys.html#sys.stdout
> 
> Here is an example:
> 
> # ================================================
> import sys
> 
> class Redirect(object):
>     def __init__(self, filename):
>         self.outfile = open(filename, 'w')
>         self.count = 0
>     def write(self, msg):
>         self.count += 1
>         self.outfile.write('%d %s\n' % (self.count, msg, ))
>     def close(self):
>         self.outfile.close()
> 
> def test():
>     print 'starting'
>     save_stdout = sys.stdout
>     redir = Redirect('/tmp/tmp1.txt')
>     sys.stdout = redir
>     print 'something'
>     print 'something else'
>     redir.close()
>     sys.stdout = save_stdout
>     print 'finished'
> 
> test()
> # ================================================

Hello,
Thank you Dave for your class, sure I will use it often.

-1- print & sys.stdout.write()
Just discovered that
   print(text)
is not equivalent to 
   sys.stdout.write(text+'\n')
but to
   sys.stdout.write(text)
   sys.stdout.write('\n')

As shown below due to line numbers. I just added a debug output to (original sys.stdout I call) console.

================
# change
class Redirect(object):
	def __init__(self, filename):
		self.console = sys.stdout
		self.outfile = open(filename, 'w')
		self.count = 0
	def write(self, msg):
		self.count += 1
		self.outfile.write('%d %s\n' % (self.count, msg, ))
		self.console.write('%d %s\n' % (self.count, msg, ))
	def close(self):
		self.outfile.close()
# ==>
Hello 
starting
1 something
2 

3 something else
4 

finished
=======================

I find this behaviour rather annoying. Requires an ugly trick to workaround.

-2- file subtype
Is there a reason why you don't make Redirect directly (lol) a subtype of file?
Actually I just tried it and got an error "bad file descriptor":

# this is my new stdout:
<open file '/tmp/tmp1.txt', mode 'r' at 0xb787dc8c>

# when trying to print:
  File "__essai__.py", line 74, in <module>
    test()
  File "__essai__.py", line 68, in test
    print 'something'
IOError: [Errno 9] Bad file descriptor

Below code of new class.

Denis


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



Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list