Tuesday, 15 November 2011

Print terminal output to file (python)

I found this awesome code snippet for python that will automatically print any print anything that is posted to the terminal to a file.

class Writer:
    def __init__(self, stdout, filename): 
        self.stdout = stdout 
        self.logfile = open(filename, 'w') 

    def write(self, text): 
        self.stdout.write(text) 
        self.logfile.write(text) 

    def close(self): 
        self.stdout.close() 
        self.logfile.close() 

This class will then inherit and modify the standard sys.stdout:
writer = Writer(sys.stdout, output_filename) 
sys.stdout = writer

No comments:

Post a Comment