Wrappers is sexy
import sys
class Logger(file):
def __init__(self,*a,**kw):
# copy original stdout to instance
self.stdout = sys.stdout
return super(Logger,self).__init__(*a,**kw)
def write(self,data):
self.stdout.write(data) # to screen
return super(Logger,self).write(data) #to file
def writelines(self,lines):
for line in lines: self.write(line)
def close(self):
# return it back
sys.stdout = self.stdout
some_list = ['elem1', 'elem2']
for elem in some_list:
with Logger("/tmp/1/{}.log".format(elem), "w") as sys.stdout:
# Do lots of stuff that print messages.
print 'lots of stuff for', elem
print 'Code finished'
Result
$ python2 out.py
Code finished
$ ls
elem1.log elem2.log out.py
Cool side effect:
print 'this on screen'
with Logger("/tmp/1/main.log", "w") as sys.stdout:
print 'this on screen an in main.log'
with Logger("/tmp/1/sub.log", "w") as sys.stdout:
print 'this on screen, in man.log and in sub.log'
print 'only on screen again'