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?
The only thing I could suggest is to use the contextmanager
decorator but I'm not convinced this is really better.
from contextlib import contextmanager
@contextmanager
def stdouterrlog(logfile):
with open(logfile, 'wb') as lf:
stdout = sys.stdout
stderr = sys.stderr
sys.stdout = lf
sys.stderr = lf
yield lf # support 'with stdouterrlog(x) as logfile'
sys.stdout = stdout
sys.stderr = stderr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With