Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w
To complete John T answer: https://stackoverflow.com/a/616686/395687
I added __enter__
and __exit__
methods to use it as a context manager with the with
keyword, which gives this code
class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def __enter__(self):
pass
def __exit__(self, _type, _value, _traceback):
pass
It can then be used as
with Tee('outfile.log', 'w'):
print('I am written to both stdout and outfile.log')