Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Can we use print to print to more than sys.stdout?

0 views
Skip to first unread message

Pierre Rouleau

unread,
Mar 12, 2002, 1:08:30 PM3/12/02
to
#1) Is it possible to change print behavior to make it print to several
streams?

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

Jason Orendorff

unread,
Mar 12, 2002, 1:25:09 PM3/12/02
to
Pierre Rouleau wrote:
> #1) Is it possible to change print behavior to make it print to several
> streams?
>
> #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?

# 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/

Fredrik Lundh

unread,
Mar 12, 2002, 2:25:14 PM3/12/02
to
Pierre Rouleau wrote:
> #1) Is it possible to change print behavior to make it print to several
> streams?

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


Pierre_...@impathnetworks.com

unread,
Mar 12, 2002, 2:49:45 PM3/12/02
to
Wow! That's got to be why i like Python so much!
Elegant, powerful and great community support with superfast turn-around time to
get questions answered!!!
Hope it would be like that for some well know Companies...
Thanks !


"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?
>

0 new messages