Skip to content

Instantly share code, notes, and snippets.

@wcang
Created April 6, 2013 06:10
Show Gist options
  • Save wcang/5325070 to your computer and use it in GitHub Desktop.
Save wcang/5325070 to your computer and use it in GitHub Desktop.
Dirty and ugly hack to duplicate stdout stream to a file. This thing sort of acts like unix's tee program. Be careful as this only overwrites several file functions
'''
Dirty and ugly hack to duplicate stdout stream to a file
Be careful as this only overwrites several file functions
This thing sort of acts like unix's tee program
Ang Way Chuang <wcang@sfc.wide.ad.jp>
Feel free to use, modify and distribute. No warranty and no restriction
'''
import sys
class Tee:
def __init__(self, file_name):
self.log_file = open(file_name, "wt", 0)
self.console = sys.stdout
sys.stdout = self
def write(self, msg):
self.log_file.write(msg)
self.console.write(msg)
def writelines(self, msg):
self.log_file.writelines(msg)
self.console.writelines(msg)
def flush(self):
self.log_file.flush()
self.console.flush()
def close(self):
self.console.close()
self.log_file.close()
if __name__ == '__main__':
Tee("sample.log")
print "hello world"
print "this is me"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment