Last active
August 29, 2015 14:12
-
-
Save YS-L/443c46459e6315aacc98 to your computer and use it in GitHub Desktop.
Multiplex stdout to a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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