I want to write the std output of a portion of Python code to a file using the 'with' statement:
with log_to_file('log'):
The easiest way to do this is to determine log_to_filemanually, for example:
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?
source
share