Created
April 6, 2013 06:10
-
-
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
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
''' | |
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