saving the text on python dos window.

Daniel Dittmar daniel.dittmar at sap.com
Thu Jun 24 13:30:28 CEST 2004


sarmin kho wrote:
> "print (text)' command will print the 'text' on dos window when
> executing a python script. i would like to save all the text printed
> on the dos window to a file at the end of the python script
> execution..

1. Create a stream class that writes anything both to sys.stdout and to a
file
2. replace sys.stdout with an instance of this class

class TeeStream:
    def __init__ (self, *outstreams):
        self.outstreams = outstreams

    def write (self, text):
        for outstream in self.outstreams:
            outstream.write (text)

    # do the same for writelines, flush etc.

import sys
mylogfile = open ('mylogfile', 'w')
sys.stdout = TeeStream (mylogfile, sys.stdout)
sys.stderr = TeeStream (mylogfile, sys.stderr)

Daniel





More information about the Python-list mailing list