-
-
Save stephenmm/45638cc9dd1002325f4d to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
import sys | |
class Tee(object): | |
""" | |
Allow forking of output to stdout and other files | |
From: http://stackoverflow.com/questions/11325019/output-on-the-console-and-file-using-python | |
@author Thrustmaster <http://stackoverflow.com/users/227884/thrustmaster> | |
@author Eric Cousineau <[email protected]> | |
""" | |
def __init__(self, *files): | |
self.files = files | |
def open(self): | |
""" Redirect stdout """ | |
if not hasattr(sys, '_stdout'): | |
# Only do this once just in case stdout was already initialized | |
# @note Will fail if stdout for some reason changes | |
sys._stdout = sys.stdout | |
sys.stdout = self | |
return self | |
def close(self): | |
""" Restore """ | |
stdout = sys._stdout | |
for f in self.files: | |
if f != stdout: | |
f.close() | |
sys.stdout = stdout | |
def write(self, obj): | |
for f in self.files: | |
f.write(obj) | |
if __name__ == '__main__': | |
print "Start..." | |
t = Tee(sys.stdout, open('/tmp/test.txt', 'w')).open() | |
print "Hello world" | |
t.close() | |
print "Goodbye" | |
""" | |
[ bash ] | |
$ python tee.py | |
Start... | |
Hello world | |
Goodbye | |
$ cat /tmp/test.txt | |
Hello world | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment