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
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()
Same basic idea:
#!/usr/bin/env python
import sys
class MyWriter:
def __init__(self, stdout, filename):
self.stdout = stdout
self.logfile = file(filename, 'a')
def write(self, text):
self.stdout.write(text)
self.logfile.write(text)
def close(self):
self.stdout.close()
self.logfile.close()
writer = MyWriter(sys.stdout, 'log.txt')
sys.stdout = writer
print 'test'
Cheers,
// m
-
Hi Mark,
works perfect. Just had to change ´file´ to ´open´ for my Python 2.1.
Adding the method ´flush(self)´ to Writer helped to get my
´sys.stdout.flush()´ to work.
Thanks also to two inches (previous post).
Mike