I\'m trying to find out a way in python to redirect the script execution log to a file as well as stdout
in a pythonic way. Is there any easy way of achieving t
You should use the logging
library, which has this capability built in. You simply add handlers to a logger to determine where to send the output.
Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")