Skip to content

Instantly share code, notes, and snippets.

@astrofrog
Created December 7, 2011 20:35
Show Gist options
  • Select an option

  • Save astrofrog/1444524 to your computer and use it in GitHub Desktop.

Select an option

Save astrofrog/1444524 to your computer and use it in GitHub Desktop.
How to redirect stdout and stderr to file for a block of code
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
self.f.close()
with log_to_file('log_1'):
# do something
with log_to_file('log_2'):
# do something else
@taldcroft

Copy link
Copy Markdown

This looks nice. A while back I did a variation on this theme to capture stdout and stderr into StringIO objects (see code below). Not clear if using the contextmanager really helped things out, but there you go. In your version maybe you could check if the passed argument is filelike and just use it directly in that case. This would allow logging into a StringIO object or whatever, not just a disk file.

@contextlib.contextmanager
def stdout_stderr():
    orig_stdout = sys.stdout
    orig_stderr = sys.stderr
    sys.stdout = StringIO.StringIO()
    sys.stderr = StringIO.StringIO()
    try:
        yield sys.stdout, sys.stderr
    finally:
        sys.stdout = orig_stdout
        sys.stderr = orig_stderr


with stdout_stderr() as stdout, stderr:
    # do something

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment