I know it is possible to change the stream where print prints by
changing the value of sys.stdout, like this:
import sys
f = open('somefile', 'w')
sys.stdout = f
print 'whatever to that file'
f.close()
#then restore stdout
sys.stdout = sys.__stdout__
But is it possible, for example, to make it print both to stdout *and*
some file?
#2)
Is it also possible to define an object that would behave like a file
and that would do the printing itself to wherever required?
Thanks!
Pierre Rouleau
# Sure. This code does both.
class Mux:
def __init__(self, *objects):
self.__objects = objects
def write(self, data):
for obj in self.__objects:
obj.write(data)
def writelines(self, lines):
for obj in self.__objects:
obj.writelines(lines)
myfile = open('somefile.txt', 'a')
sys.stdout = Mux(sys.stdout, myfile)
## Jason Orendorff http://www.jorendorff.com/
class Tee:
def __init__(self, *streams):
self.streams = streams
def write(self, text):
for stream in self.streams:
stream.write(text)
sys.stdout = Tee(sys.stdout, open("some.file", "w"), ...)
</F>
<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
"Jason Orendorff" <ja...@jorendorff.com> on 03/12/2002 01:25:09 PM
To: Pierre Rouleau/impath@impath, "python-list" <pytho...@python.org>
cc:
Subject: Re: Can we use print to print to more than sys.stdout?
Pierre Rouleau wrote:
> #1) Is it possible to change print behavior to make it print to several
> streams?
>