Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Forked from eacousineau/tee.py
Last active August 29, 2015 14:12
Show Gist options
  • Save stephenmm/45638cc9dd1002325f4d to your computer and use it in GitHub Desktop.
Save stephenmm/45638cc9dd1002325f4d to your computer and use it in GitHub Desktop.
#!/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