Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging stdout and stderr to log file using Python 'with' statement

Tags:

python

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?

like image 469
astrofrog Avatar asked Nov 05 '22 09:11

astrofrog


1 Answers

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
like image 185
wberry Avatar answered Nov 09 '22 13:11

wberry