print to screen and file with one print statement
Two Inches
missedby2inches at gmx.net
Wed Feb 12 16:34:46 EST 2003
How about this:
class writer :
def __init__(self, *writers) :
self.writers = writers
def write(self, text) :
for w in self.writers :
w.write(text)
import sys
saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There you go."
sys.stdout = saved
fout.close()
Mike Müller wrote:
> I would like to send my print statements to the terminal and to a log
> file at the same time. I can use redirect as describe in Dive into
> Python:
>
> import sys
>
> print 'Dive in'
> saveout = sys.stdout
> fsock = open('out.log', 'w')
> sys.stdout = fsock
> print 'This message will be logged but not displayed'
> print 'This message should be logged and also displayed'
> sys.stdout = saveout
> fsock.close()
>
> This redirects all output from Python to the open file.
> At the same time I'd like to see all printed text on screen.
> How can I do this?
>
> Thanks
>
> Mike
More information about the Python-list
mailing list