Skip to content

Instantly share code, notes, and snippets.

@YS-L
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YS-L/443c46459e6315aacc98 to your computer and use it in GitHub Desktop.
Save YS-L/443c46459e6315aacc98 to your computer and use it in GitHub Desktop.
Multiplex stdout to a file
from traceback import print_exception
class Tee(object):
""" Multiplex stdout to a file
Possibly useful for inspecting the output of a long running python process started via IPython.
Adapted from answers found in SO questions [1] and [2].
[1] http://stackoverflow.com/questions/616645/how-do-i-duplicate-sys-stdout-to-a-log-file-in-python
[2] http://stackoverflow.com/questions/14571090/ipython-redirecting-output-of-a-python-script-to-a-file-like-bash
"""
def __init__(self, name, mode='w'):
self.name = name
self.mode = mode
def __enter__(self):
self.file_handle = open(self.name, self.mode)
self.terminal = sys.stdout
sys.stdout = self
def __exit__(self, exc_type, exc_value, traceback):
print_exception(exc_type, exc_value, traceback,
None, self.file_handle)
self.flush()
self.file_handle.close()
sys.stdout = self.terminal
def write(self, data):
self.file_handle.write(data)
self.terminal.write(data)
self.flush()
def flush(self):
self.file_handle.flush()
self.terminal.flush()
print 'Print only to stdout'
with Tee('tee.txt'):
print 'Now print to both stdout and the tee-ed file'
print '(Go tail -F this file already)'
import time
for i in range(5):
print 'Output #{}'.format(i)
time.sleep(0.5)
raise ValueError('kthxbye')
for i in range(5):
print 'Print only to stdout again'
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment