Writing stdout and stderr to a log file using a Python statement with '

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'):
    # execute code

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?

+5
source share
1 answer

The only thing I could suggest was to use a decorator contextmanager, but I'm not sure if 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
+2
source

All Articles