I want to log the std output of a chunk of Python code to a file, using the 'with' statement:
with log_to_file('log'):
# execute code
Is the easiest way to do this to define the log_to_file
manually, e.g.:
import sys
class log_to_file():
def __init__(self, filename):
self.f = open(filename, 'wb')
def __enter__(self):
self.stdout = sys.stdout
self.stderr = sys.stderr
sys.stdout = self.f
sys.stderr = self.f
def __exit__(self, type, value, traceback):
sys.stdout = self.stdout
sys.stderr = self.stderr
or is there a built-in class that can do this already?